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.
这里看到题目中除了getMin(),其他的stack都已经实现了,那么我们只需要实现这一接口即可。
可以在用个stack来记录当前stack中最小值。
class MinStack {
private:
stack<int> stac;
stack<int> min;
public:
void push(int x) {
stac.push(x);
if(min.empty()||x<=min.top())//注意这里的等于号不能漏掉哦。
min.push(x);
}
void pop() {
if(stac.empty()) return;
if(stac.top() == min.top())
min.pop();
stac.pop();
}
int top() {
return stac.top();
}
int getMin() {
return min.top();
}
};