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 {
private:
stack<int> data;
stack<int> minStk;
public:
void push(int x) {
data.push(x);
if(x <= getMin())
minStk.push(x);
}
void pop() {
if(!data.empty())
{
if(data.top() == minStk.top())
{
minStk.pop();
}
data.pop();
}
}
int top() {
if(!data.empty())
return data.top();
return 0;
}
int getMin() {
if(!minStk.empty())
return minStk.top();
return INT_MAX;
}
};
浙公网安备 33010602011771号