题目:
解答:
采用双栈的办法以空间换时间,栈s1作为普通的数据栈,栈s2用来保存每次入栈时的较小值,这样s2栈顶的值总是栈中元素的最小值。
1 class MinStack { 2 public: 3 /** initialize your data structure here. */ 4 MinStack() 5 { 6 7 } 8 9 void push(int x) 10 { 11 s1.push(x); 12 if(s2.empty()) 13 { 14 s2.push(x); 15 } 16 else 17 { 18 int t = s2.top(); 19 s2.push((x < t) ? x : t); 20 } 21 } 22 23 void pop() 24 { 25 s1.pop(); 26 s2.pop(); 27 } 28 29 int top() 30 { 31 return s1.top(); 32 } 33 34 int getMin() 35 { 36 return s2.top(); 37 } 38 private: 39 stack<int> s1; 40 stack<int> s2; 41 }; 42 43 /** 44 * Your MinStack object will be instantiated and called as such: 45 * MinStack* obj = new MinStack(); 46 * obj->push(x); 47 * obj->pop(); 48 * int param_3 = obj->top(); 49 * int param_4 = obj->getMin(); 50 */
原文:https://www.cnblogs.com/ocpc/p/12832999.html