LeetCode 155 : Min Stack (Java)

解题思路:用java写的话有个需要注意的地方就是由于Stack中的元素用了泛型,而泛型不支持基本类型,所以需要基本类型的包装类。而包装类不同于基本类型的是包装类是引用,要比较相等不能简单使用==,要使用equals方法。
LeetCode官网unlock的提示:
Hints:

Consider space-time tradeoff. How would you keep track of the minimums using extra space?
Make sure to consider duplicate elements.

O(n) runtime, O(n) space – Extra stack:

Use an extra stack to keep track of the current minimum value. During the push operation we choose the new element or the current minimum, whichever that is smaller to push onto the min stack.
O(n) runtime, O(n) space – Minor space optimization:

If a new element is larger than the current minimum, we do not need to push it on to the min stack. When we perform the pop operation, check if the popped element is the same as the current minimum. If it is, pop it off the min stack too.

class MinStack {
    private Stack<Integer> stack = new Stack<>();
    private 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();        
    }
}

你可能感兴趣的:(stack)