【重温经典】最小栈

【重温经典】最小栈

方法1:辅助栈[浪费空间]

  • 基础版辅助栈,准备一个data, 数据栈,准备一个help 辅助栈

  • 其中data的存数据的,help辅助栈用来存最小值,在push操作时,help如果栈顶元素大于待push的元素,将待push的元素塞进help中,如果不是,则重复塞一次help的栈顶元素,注意help为空的时候特殊处理下

在这里插入图片描述

  • 准备两个栈,data和help,做push操作时,需要保持help栈顶的元素始终最小,data的数据正常推入,help栈顶维持最小,在执行getMin方法的时候,返回help的栈顶元素
class MinStack {
        private Stack<Integer> data;
        private Stack<Integer> help;

        /**
         * initialize your data structure here.
         */
        public MinStack() {
            data = new Stack<>();
            help = new Stack<>();
        }

        public void push(int x) {
            data.push(x);
            if (help.isEmpty()) help.push(x);
            else if (help.peek() < x) help.push(help.peek());
            else help.push(x);
        }

        public void pop() {
            if (data.isEmpty()) throw new RuntimeException("stack empty");
            data.pop();
            help.pop();
        }

        public int top() {
            if (data.isEmpty()) throw new RuntimeException("stack empty");
            return data.peek();

        }

        public int getMin() {
            if (data.isEmpty()) throw new RuntimeException("stack empty");
            return help.peek();
        }
    }
方法2:辅助栈[不浪费空间]
  • 升级版本辅助栈,当push 进去的时候,
    • help的栈顶元素比新来的元素小的时候,这个时候保持help不变
    • help的栈顶元素大于等于新来的元素时,help同步要推一份新的元素进来
    • help元素为空的时候,也需要往里推
  • pop的时候,pop的元素是否和help 的元素有重叠,有就将help的元素pop出去,没有就维持不动,data栈正常pop
class MinStack {
    Stack<Integer> data;
    Stack<Integer> help;

    /**
     * initialize your data structure here.
     */
    public MinStack() {
        data = new Stack<>();
        help = new Stack<>();
    }

    public void push(int x) {
        if (help.isEmpty() || help.peek() >= x) {
            help.push(x);
        }
        data.push(x);

    }

    public void pop() {
        if (data.isEmpty()) throw new RuntimeException("The stack is empty");
        int pop = data.pop();
        if (pop == help.peek()) {
            help.pop();
        }
    }

    public int top() {
        if (data.isEmpty()) throw new RuntimeException("The stack is empty");
        return data.peek();
    }

    public int getMin() {
        if (help.isEmpty()) throw new RuntimeException("The stack is empty");
        return help.peek();
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值