题目呈现如下:
比较简单,直接上代码.
下附AC代码:
// 采用辅助栈
// 我们需要保存最新的最小值,同时能够保存上个最小值以及上上个最小值..
// 符合FILO(先进后出,后进先出)原则,所以我们也同样用栈来记录最小值
class MinStack {
public:
/** initialize your data structure here. */
stack<int> s;
stack<int> min_s;
MinStack() {
min_s.push(INT_MAX);
}
void push(int x) {
s.push(x);
int cur_min = min_s.top();
if(x<=cur_min) min_s.push(x);
}
void pop() {
int toPop = s.top();
s.pop();
int cur_min = min_s.top();
if(toPop == cur_min) min_s.pop();
}
int top() {
return s.top();
}
int getMin() {
return min_s.top();
}
};
/**
* 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();
*/