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) {
if(stack_.empty())
{
minValues_.push_back(x);
}
else if(minValues_.back() < x)
{
minValues_.push_back(minValues_.back());
}
else
{
minValues_.push_back(x);
}
stack_.push_back(x);
}
void pop() {
stack_.pop_back();
minValues_.pop_back();
}
int top() {
return stack_.back();
}
int getMin() {
return minValues_.back();
}
vector<int> stack_;
vector<int> minValues_;
};