[LeetCode]Min Stack,解题报告

65 篇文章 1 订阅

目录


题目

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.

思路1

这道题算是面试过程中比较简单的题目,在实现基础栈的基础上,增加了一个在O(1)时间复杂度下获取当前栈内最小值的需求。
很自然的可以想到,可以用ArrayList来构建stack,同时用一个int类型的变量minIndex作为当前最小值的下标。

  • 每次push(x)操作时,判断是否需要更新minIndex。
  • 每次pop操作时,判断当前移除的是否为minIndex,如果是,则需要O(n)时间复杂度更新minIndex。

思路有了,我们可以先写代码尝试一下,这种思路是否可以AC这道题目。

AC代码

import java.util.ArrayList;


public class MinStack {
    private ArrayList<Integer> stack = new ArrayList<Integer>();
    private int minIndex = 0;

    public void push(int x) {
        stack.add(x);
        if (x < stack.get(minIndex) || stack.size() == 1) {
            minIndex = stack.size() - 1;
        }
    }

    public void pop() {
        if (minIndex == stack.size() - 1) {
            minIndex = 0;
            for (int i = 1; i < stack.size() - 1; i ++) {
                if (stack.get(i) < stack.get(minIndex)) {
                    minIndex = i;
                }
            }
        }

        stack.remove(stack.size() - 1);
    }

    public int top() {
        return stack.get(stack.size() - 1);
    }

    public int getMin() {
        return stack.get(minIndex);
    }
}

缺陷

虽然上面的代码可以AC,而且getMin()方法的时间复杂度是O(1),但是我们在pop方法中,当需要更新minIndex时,花费的时间复杂度是O(n),严格的说,上面的代码是不符合面试要求的。
减少时间复杂度最便捷的方法就是增加空间复杂度,很自然的我们想到“双栈法”。再维护一个最小数的栈,这样更新minIndex的操作我们可以通过最小数出栈的方式来搞定了。


思路2

双栈法的思路是:增加一个最小栈。当最小栈为空或者当前push元素小于等于最小栈栈顶元素时,该push元素也要push到最小栈中。

AC代码

import java.util.Stack;

public class MinStack {
    private Stack<Integer> normalStack = new Stack<Integer>();
    private Stack<Integer> minStack = new Stack<Integer>();

    public void push(int x) {
        if (minStack.size() == 0 || x <= minStack.peek()) {
            minStack.push(x);
        }
        normalStack.push(x);
    }

    public void pop() {
        if (normalStack.peek().equals(minStack.peek())) {
            minStack.pop();
        }

        normalStack.pop();
    }

    public int top() {
        return normalStack.peek();
    }

    public int getMin() {
        return minStack.peek();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值