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:
//用vector实现似乎比stack快
stack<int> s;
stack<int> min;
void push(int x) {
if(s.empty()){
min.push(x);
}
else if(min.top()>=x)min.push(x);
s.push(x);
}
void pop() {
int temp=s.top();
s.pop();
if(temp==min.top())min.pop();
}
int top() {
return s.top();
}
int getMin() {
return min.top();
}
};