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.
思路分析:这题主要考察栈的使用,唯一tricky的地方是如何在常数时间内得到最小值,我们可以考虑使用两个栈,一个栈seqStack用于维护入栈的顺序,操作同普通的栈,另一个minStack栈用于维护最小值,当出现比栈顶元素更小或者相等的数的时候,要入栈,使得栈顶元素总是最小值。这样getMin函数只要取维护最小值栈的栈顶元素即可。有一个容易出错的地方是删除元素的时候除了从seqStack里面删除栈顶元素之外,还需要从minStack的栈顶做检查,如果删除的刚好是最小元素,应该把minStack的栈顶也删除。
AC Code
class MinStack {
Stack<Integer> seqStack = new Stack<Integer>();
Stack<Integer> minStack = new Stack<Integer>();
public void push(int x) {
int curMin;
if(minStack.isEmpty()){
curMin = Integer.MAX_VALUE;
} else{
curMin = minStack.peek();
}
if(x <= curMin) minStack.push(x);
seqStack.push(x);
}
public void pop() {
if(seqStack.isEmpty()) return;
else {
int removedValue = seqStack.pop();
if(removedValue == minStack.peek()){
minStack.pop();
}
}
}
public int top() {
return seqStack.peek();
}
public int getMin() {
return minStack.peek();
}
}