Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack.
首先,想到的是,对于一个普通栈来说,不能实现O(1)找最小值。需要辅助,采用双栈:
Real stack Min stack
5 --> TOP 1
4 1
1 1
3 2
2 2
辅助栈每次存入当前最小值,并同步压入和弹出即可。
但是以上问题是:Memory Limit Exceeded(消耗了2倍的空间)
优化: Min Stack 不必每次都存入,只需要存入最小值变化的状态。
Real stack Min stack
5 --> TOP 1
4 2
1
3
2
所以每次出栈的时要比较一下,
入栈时 curr< = Min Stack Top 则MinStack 也要入栈
如果Real Stack top == Min Stack top 则 Min Stack 也需要pop()
注意:最小值可能会多次入栈的问题。
class MinStack{
public:
void push(int x) {
S.push(x);
if(MinS.empty() || x<=MinS.top())
MinS.push(x);
}
void pop(){
int temp=S.top();
S.pop();
if(temp == MinS.top())
MinS.pop();
}
int top(){
return S.top();
}
int getMin(){
return MinS.top();
}
private:
stack<int> S,MinS;
};