标签:
这里面有一个注意的点是,如果现在要push x,且x等于当前存在的最小值(栈中已经有了x)时,也要把x进栈。否则当x出栈时,当前最小值也跟着出栈,但是原栈中最小值元素依然还有,此时最小值却发生了错误。
class MinStack { public: /** initialize your data structure here. */ MinStack() { } void push(int x) { s1.push(x); if(!s2.size()) s2.push(x); else if(x<=s2.top()) s2.push(x); } void pop() { if(s1.size()) { if(s1.top()==s2.top()) { s1.pop(); s2.pop(); } else s1.pop(); } } int top() { return s1.top(); } int getMin() {return s2.top(); } private: stack<int> s1; stack<int> s2; }; /** * 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(); */
标签:
原文地址:http://www.cnblogs.com/summerkiki/p/5518229.html