题目地址:https://leetcode.com/problems/min-stack/
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.
Example:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> Returns -3.
minStack.pop();
minStack.top(); --> Returns 0.
minStack.getMin(); --> Returns -2.
堆栈几个操作本身的实现问题不是很大,用LinkedList提供的方法基本就能搞定了,但是这里多了一个getMin方法,如果是每次调用getMin的时候都要从栈顶扫描到栈底去找最小值,那么这样是十分耗时的,那么我们就应该想办法在元素入栈的时候就想办法保存下来。
我们可以再设这样一个栈,这个栈根据上一个栈的push操作,如果出现更小的数字,则minStack执行push,如果上一个栈执行pop且pop出来的值等于minStack栈顶的值,那么minStack也执行pop操作,这样的话getMin的具体实现就是minStack.getFirst()啦,时间复杂度为O(1):
public class MinStack {
/** initialize your data structure here. */
LinkedList<Integer> stack = new LinkedList<>();
LinkedList<Integer> minStack = new LinkedList<>();
public MinStack() {
}
public void push(int x) {
stack.push(x);
if (minStack.size() == 0)
minStack.push(x);
else {
if (minStack.getFirst() >= x)
minStack.push(x);
}
}
public void pop() {
int x = stack.pop();
if (x == minStack.getFirst()){
minStack.pop();
}
}
public int top() {
return stack.getFirst();
}
public int getMin() {
return minStack.getFirst();
}
public static void main(String[] args) {
MinStack stack = new MinStack();
stack.push(1);
stack.push(2);
stack.push(-3);
System.out.println(stack.getMin());
stack.pop();
System.out.println(stack.top());
stack.pop();
System.out.println(stack.top());
}
}
/**
* 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();
*/