https://leetcode-cn.com/problems/min-stack/
思路:用兩個棧,第一個棧正常做棧的操作,第二個棧維持一個單調非升的序列,從而保證最小值就在的棧頂,現在考慮怎麼維護第二個棧,如果爲空或者當前要壓入的元素,那麼直接將其壓到第二個棧內,否則不做任何操作即可。
class MinStack {
public:
/** initialize your data structure here. */
stack<int> s1;
stack<int> s2; //單調下降棧
MinStack() {
}
void push(int x) {
s1.push(x);
if(s2.empty()||x<=s2.top())
s2.push(x);
}
void pop() {
int val=s1.top();
s1.pop();
if(val==s2.top())
s2.pop();
}
int top() {
return s1.top();
}
int getMin() {
return s2.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();
*/