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:
stack<int> myStack;
stack<int> minStack;
void push(int x) {
myStack.push(x);
if(minStack.empty() || minStack.top()>=x)
minStack.push(x);
}
void pop() {
if(myStack.top() == minStack.top())
minStack.pop();
myStack.pop();
}
int top() {
return myStack.top();
}
int getMin() {
return minStack.top();
}
};