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.
思路:利用两个栈,一个栈存储数据,一个栈采用DP的思想,动态存储当前数据的最小值,这样相当于实现了O(1)的最小值。
class MinStack {
public:
void push(int x) {
data.push(x);
if(min.size()==0) //空的时候压入最小栈
min.push(x);
else
{
if(x<min.top())
{
min.push(x);
}
else if(x>=min.top())
min.push(min.top());
}
}
void pop() {
data.pop();
min.pop();
}
int top() {
return data.top();
}
int getMin() {
return min.top();
}
private:
stack<int> data;
stack<int> min;
};