设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
使用两个栈 s1, s2,s1 正常的入栈出栈,s2存放s1中所有节点的最小值。
入栈
出栈
获取最小值
直接就是 s2 的栈顶元素。
#include
#include
#include
using namespace std;
class MinStack {
public:
stack<int> s1, s2;
MinStack() {
}
void push(int x) {
s1.push(x);
if(s2.empty() || x <= s2.top())
{
s2.push(x);
}
}
void pop() {
if(s1.top() == s2.top())
s2.pop();
s1.pop();
}
int top() {
return s1.top();
}
int getMin() {
return s2.top();
}
};