JZ30. 包含min函数的栈

73 阅读1分钟

leetcode.cn/problems/ba…

定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。

 

示例:

MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.min(); --> 返回 -3. minStack.pop(); minStack.top(); --> 返回 0. minStack.min(); --> 返回 -2.  

提示:

各函数的调用总次数不超过 20000 次

解题思路:

image.png

image.png

image.png

复杂度分析

时间复杂度 O(1) : push(), pop(), top(), min() 四个函数的时间复杂度均为常数级别。

空间复杂度 O(N) : 当共有 N 个待入栈元素时,辅助栈 B 最差情况下存储 N 个元素,使用 O(N) 额外空间。

代码:

Java 代码中,由于 Stack 中存储的是 int 的包装类 Integer ,因此需要使用 equals() 代替 == 来比较值是否相等。

class MinStack {

    Stack<Integer> stack1;
    Stack<Integer> stack2;

    /**
     * initialize your data structure here.
     */
    public MinStack() {
        stack1 = new Stack();
        stack2 = new Stack();
    }

    public void push(int x) {
        stack1.push(x);
        if (stack2.isEmpty() || x <= stack2.peek()) {
            stack2.push(x);
        }
    }

    public void pop() {
        if (stack1.peek().equals(stack2.peek())) {
            stack2.pop();
        }
        stack1.pop();
    }

    public int top() {
        if (stack1.isEmpty()) {
            return -1;
        } else {
            return stack1.peek();
        }
    }

    public int min() {
        if (stack2.isEmpty()) {
            return -1;
        } else {
            return stack2.peek();
        }
    }
}