Problem
How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop and min should all operate in 0(1) time.
Example
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> return -3.
minStack.pop();
minStack.top(); --> return 0.
minStack.getMin(); --> return -2.
Solution
使用两个栈,s1记录数据,s2记录当前数据对应的最小值。
当有新元素入栈时,直接将其压入s1;
对于s2,将新元素与其栈顶元素相比较,将二者中较小的压入。
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
val_s.push(x);
if(min_s.empty())
{
min_s.push(x);
}
else
{
int curMin = min_s.top();
if(x < curMin)
min_s.push(x);
else
min_s.push(curMin);
}
}
void pop() {
if(!val_s.empty())
{
val_s.pop();
min_s.pop();
}
}
int top() {
return val_s.top();
}
int getMin() {
return min_s.top();
}
stack<int> min_s;
stack<int> val_s;
};
/**
* 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();
*/
Related problem
面试题59 - II. 队列的最大值