当前位置:网站首页>Lecture 1: stack containing min function
Lecture 1: stack containing min function
2022-07-07 09:32:00 【Fight! Sao Nian!】
subject :AcWing 41. contain min Function of the stack
Design a support push,pop,top Wait for operation and can be in O(1) Retrieve the stack of the smallest elements in time .
push(x)– Put the element x Insert into the stack
pop()– Remove the top element
top()– Get the stack top element
getMin()– Get the smallest element in the stack
Data range
Total number of operation commands [0,100].
Examples
MinStack minStack = new MinStack();
minStack.push(-1);
minStack.push(3);
minStack.push(-4);
minStack.getMin(); --> Returns -4.
minStack.pop();
minStack.top(); --> Returns 3.
minStack.getMin(); --> Returns -1.
Topic analysis :
If this problem does not return the minimum value, then we can directly use the stack , What if you need to return the minimum value ?
We can use auxiliary stack
The sub group stack only stores elements smaller than the top element , Then the top of the auxiliary stack is the minimum value of the current stack .
According to the following figure, we can intuitively feel the relationship between stack and auxiliary stack .
Even if 3 Pop up stack , that 41 Will become the smallest value of the current stack .
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
stk.push(x);
if(min_stk.empty()||min_stk.top()>=x)min_stk.push(x);
}
void pop() {
if(min_stk.top()==stk.top())min_stk.pop();
stk.pop();
}
int top() {
return stk.top();
}
int getMin() {
return min_stk.top();
}
private:
stack<int> stk,min_stk;
};
/** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */
边栏推荐
- Implementation of corner badge of Youmeng message push
- 第一讲:包含min函数的栈
- Huawei hcip datacom core_ 03day
- JWT certification used in DRF
- JMeter JDBC batch references data as input parameters (the simplest method for the whole website)
- Oracle安装增强功能出错
- Variable parameter of variable length function
- 软件建模与分析
- 信息安全实验一:DES加密算法的实现
- **grafana安装**
猜你喜欢
随机推荐
战略合作|SubQuery 成为章鱼网络浏览器的秘密武器
超十万字_超详细SSM整合实践_手动实现权限管理
Unity3d interface is embedded in WPF interface (mouse and keyboard can respond normally)
Some pit avoidance guidelines for using Huawei ECS
Colorbar of using vertexehelper to customize controls (II)
Netease cloud wechat applet
Loxodonframework quick start
[cloud native] Devops (I): introduction to Devops and use of code tool
数据库多表关联查询问题
Dynamics 365online applicationuser creation method change
【云原生】DevOps(一):DevOps介绍及Code工具使用
Oracle安装增强功能出错
12、 Sort
Niuke - Huawei question bank (61~70)
Difference between interface iterator and iteratable
scrapy爬虫mysql,Django等
【SVN】SVN是什么?怎么使用?
Cesium load vector data
Jenkins automated email
Connecting mobile phone with ADB