思路:
最小值更新之前先把之前老的最小值存一份。
实现:
1 class MinStack { 2 public: 3 /** initialize your data structure here. */ 4 int minn = INT_MAX; 5 stack<int> s; 6 MinStack() { 7 8 } 9 10 void push(int x) { 11 if (x <= minn) { 12 s.push(minn); 13 minn = x; 14 } 15 s.push(x); 16 } 17 18 void pop() { 19 if (s.top() == minn) { s.pop(); minn = s.top(); } 20 s.pop(); 21 } 22 23 int top() { 24 return s.top(); 25 } 26 27 int getMin() { 28 return minn; 29 } 30 }; 31 32 /** 33 * Your MinStack object will be instantiated and called as such: 34 * MinStack obj = new MinStack(); 35 * obj.push(x); 36 * obj.pop(); 37 * int param_3 = obj.top(); 38 * int param_4 = obj.getMin(); 39 */