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.
解题思路:用一个单调的栈,栈低为最大值,其TOP为当前栈里的最小值,然后每加入一个元素,就要与栈顶元素比较,如果小于栈顶元素,就入栈,否则不入栈。
so easy...
class MinStack {
public:
void push(int x) {
sta.push(x);
if(min_sta.empty()||x<=min_sta.top())/*新栈为空时要压入第一个元素,之后要压入最小的值*/
min_sta.push(x);
}
void pop() {
if(sta.top()==min_sta.top())/*注意检测最小值时候已经弹出*/
{
min_sta.pop();
}
sta.pop();
}
int top() {
return sta.top();
}
int getMin() {
return min_sta.top();
}
stack<int> sta;
stack<int> min_sta;
};