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.
这道题的主要思考方向为,如果一次次遍历求出最小值的时间复杂度是O(n),现采用时间复杂度为O(1)的算法进行求解该题目。
思路:
class MinStack {
Stack<Integer> stack;
Stack<Integer> minStack;
public MinStack() {
stack=new Stack<Integer>();
minStack=new Stack<Integer>();
}
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();
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
注意:
Stack不能用基本类型初始化,运用了泛型,而泛型不支持基本类型,所以需要基本类型的包装类。而包装类不同于基本类型的是包装类是引用,要比较相等不能简单使用= =,要使用equals方法。