题目:
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.
题目要求retrieving the minimum element in constant time.从而需要保存一个保存最小值的栈
class MinStack {
// stack:
private Stack<Integer> stack = new Stack<Integer>();
// minStack:
private Stack<Integer> minStack = new Stack<Integer>();
public void push(int x) {
if (minStack.isEmpty() || x <=minStack.peek())//stack.peek()返回stack顶部对象但不移除
minStack.push(x);
stack.push(x);
}
public void pop() {
if (stack.peek().equals(minStack.peek()))
minStack.pop();
stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}
对于if (minStack.isEmpty() || x <=minStack.peek()),需要注意,这里是“<=”而不是“=”。