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.
设置2个栈,一个存放数据,一个栈用栈顶存放当前的最小值,解法如下(没有考虑栈空之类的情况,OJ上反正AC了)
<pre name="code" class="cpp">class MinStack {
public:
void push(int x) {
realStack.push(x);
if(minStack.empty() || minStack.top()>=x)//注意realStack和minStack的元素个数不一定是相同的,如果用相同的那种方法,可能会MLE
minStack.push(x);
}
void pop() {
int topVal=realStack.top();
realStack.pop();
if(topVal<=minStack.top())
minStack.pop();
}
int top() {
return realStack.top();
}
int getMin() {
return minStack.top();
}
private:
stack<int> realStack,minStack;
};