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.
思路:两个栈,stmin保存的永远是当前所有元素中最小的。
c++实现:
class MinStack {
public:
void push(int x) {
stnor.push(x);
if(stmin.empty() || stmin.top() >= x)
stmin.push(x);
}
void pop() {
int top = stnor.top();
stnor.pop();
if(top <= stmin.top())
stmin.pop();
}
int top() {
return stnor.top();
}
int getMin() {
return stmin.top();
}
private:
stack stnor;
stack stmin;
};