问题描述:
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.
思路:
刚开始想到的方法是遍历整个栈,将最小值返回,最后想到以前的一道题目和这到题目类似,果断采取了两个栈,一个放最小值。有一个地方是需要特别注意的:
if(stack.peek().equals(minstack.peek()))这里用到了一个函数equals,目的是比较二者大小。
JAVA代码:
class MinStack {
Stack<Integer> stack = new Stack<>();
Stack<Integer> minstack = new Stack<>();
public void push(int x) {
if(minstack.isEmpty() || x <= minstack.peek())
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();
}
}