LeetCode 155 : Min Stack (Java)

本文介绍了一种使用两个栈来实现在O(1)时间内获取最小元素的数据结构。通过一个主栈存储所有元素,并使用另一个辅助栈跟踪当前最小值。这种方法确保了在插入、删除和查询最小值操作上都能达到O(n)的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解题思路:用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();        
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值