题目:
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.
在普通栈的基础上增加一个最小栈,存储最小值即可。要注意,java中Integer型变量比较的是内存地址,要使用.intValue()方法
代码:
class MinStack {
private Stack<Integer> stack = new Stack<Integer>();
private Stack<Integer> minStack = new Stack<Integer>();
public void push(int x) {
stack.push(x);
if(minStack.isEmpty() || x <= minStack.peek())
minStack.push(x);
}
public void pop() {
if(minStack.peek().intValue == stack.pop().intValue())
minStack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}