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.
依然是用两个栈来满足。其中一个栈正常存放所有元素,另一个栈存放当前栈内的最小元素(在pop的时候需要判断)
class MinStack {
public:
stack<int> stk1;
stack<int> stk2;
void push(int x) {
stk1.push(x);
if(stk2.empty()||stk2.top()>=x)
stk2.push(x);
}
void pop() {
if(stk1.top()==stk2.top())
stk2.pop();
stk1.pop();
}
int top() {
return stk1.top();
}
int getMin() {
return stk2.top();
}
};