标签:private ret min() you call obj anti 辅助 []
1 static int wing=[]() 2 { 3 std::ios::sync_with_stdio(false); 4 cin.tie(NULL); 5 return 0; 6 }(); 7 8 class MinStack 9 { 10 private: 11 stack<int> s1; 12 stack<int> s2; 13 14 public: 15 /** initialize your data structure here. */ 16 17 void push(int x) 18 { 19 s1.push(x); 20 if(s2.empty()||x<=getMin()) 21 s2.push(x); 22 } 23 24 void pop() 25 { 26 if(s1.top()==getMin()) 27 s2.pop(); 28 s1.pop(); 29 } 30 31 int top() 32 { 33 return s1.top(); 34 } 35 36 int getMin() 37 { 38 return s2.top(); 39 } 40 }; 41 42 /** 43 * Your MinStack object will be instantiated and called as such: 44 * MinStack obj = new MinStack(); 45 * obj.push(x); 46 * obj.pop(); 47 * int param_3 = obj.top(); 48 * int param_4 = obj.getMin(); 49 */
这个最小栈和普通栈操作差不多,只是多了个getMin()函数用来获取栈内最小值。
为了完成获取最小值的函数,需要借助一个辅助栈来存放当前栈内最小值。
标签:private ret min() you call obj anti 辅助 []
原文地址:https://www.cnblogs.com/zhuangbijingdeboke/p/9066404.html