本题题目要求如下:
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) {
normalStack.push(x);
if (minStack.empty() or minStack.top() >= x) {
minStack.push(x);
}
}
void pop() {
if (normalStack.top() == minStack.top()) {
minStack.pop();
}
normalStack.pop();
}
int top() {
return normalStack.top();
}
int getMin() {
return minStack.top();
}
private:
stack<int> normalStack;
stack<int> minStack;
};