题目:
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.
class MinStack {
public:
void push(int x) {
ordinaryStack.push(x);
if (minStack.empty() || x < minStack.top()) minStack.push(x);
else minStack.push(minStack.top());
}
void pop() {
ordinaryStack.pop();
minStack.pop();
}
int top() {
return ordinaryStack.top();
}
int getMin() {
return minStack.top();
}
private:
stack<int> ordinaryStack;
stack<int> minStack;
};