要求:获取最小值O(1)
思路:要额外维护一个最小值栈
class MinStack {
private:
stack<int> s;
stack<int> mins;
int minval;
public:
MinStack() {
minval=0x7fffffff;
}
void push(int val) {
s.push(val);
minval=min(val,minval);
mins.push(minval);
}
void pop() {
s.pop();
mins.pop();
minval=mins.empty()?0x7fffffff:mins.top();
}
int top() {
return s.top();
}
int getMin() {
return minval;
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(val);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/