剑指 Offer 30. 包含min函数的栈
思路
方法一:辅助栈 (单调栈)
这里参考:面试题30. 包含 min 函数的栈(辅助栈,清晰图解)
相似题目:剑指 Offer 59 - I. 滑动窗口的最大值
1 class MinStack { 2 private: 3 stack<int> A; 4 stack<int> B; 5 public: 6 /** initialize your data structure here. */ 7 MinStack() { 8 9 } 10 11 void push(int x) { 12 A.push(x); 13 //这里不能写x < B.top(),否则下面这种输入过不了 14 /* 15 ["MinStack","push","push","push","getMin","pop","getMin"] 16 [[],[0],[1],[0],[],[],[]] 17 */ 18 if(B.empty() || x <= B.top()) { 19 B.push(x); 20 } 21 } 22 23 void pop() { 24 if(A.top() == B.top()) 25 B.pop(); 26 A.pop(); 27 } 28 29 int top() { 30 return A.top(); 31 } 32 33 int getMin() { 34 return B.top(); 35 } 36 }; 37 38 /** 39 * Your MinStack object will be instantiated and called as such: 40 * MinStack* obj = new MinStack(); 41 * obj->push(x); 42 * obj->pop(); 43 * int param_3 = obj->top(); 44 * int param_4 = obj->getMin(); 45 */
方法二:一个栈同时保存当前值和栈内最小值
这里参考:一个栈同时保存当前值和栈内最小值
1 class MinStack { 2 private: 3 stack<pair<int, int>> S; 4 public: 5 /** initialize your data structure here. */ 6 MinStack() { 7 8 } 9 10 void push(int x) { 11 if(S.empty()) 12 S.push(make_pair(x, x)); 13 else 14 S.push( make_pair(x, std::min(x, S.top().second)) ); 15 } 16 17 void pop() { 18 S.pop(); 19 } 20 21 int top() { 22 return S.top().first; 23 } 24 25 int min() { 26 return S.top().second; 27 } 28 }; 29 30 /** 31 * Your MinStack object will be instantiated and called as such: 32 * MinStack* obj = new MinStack(); 33 * obj->push(x); 34 * obj->pop(); 35 * int param_3 = obj->top(); 36 * int param_4 = obj->min(); 37 */