leetcode栈的最小值
程序员文章站
2022-06-03 13:57:34
...
1.双栈
一个栈保存元素,一个栈保存最小值
代码如下:
class MinStack {
stack<int> data;
stack<int> minstack;
public:
/** initialize your data structure here. */
MinStack() {
// data=new stack<>();
// minstack=new stack<>();
}
void push(int x) {
data.push(x);
if(minstack.empty()||x<minstack.top())//最小栈为空或当前元素小于栈顶元素
minstack.push(x);
else
minstack.push(minstack.top());
}
void pop() {
data.pop();
minstack.pop();
}
int top() {
return data.top();
}
int getMin() {
return minstack.top();
}
};
/**
* 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();
*/
2.