LeetCode 155最小栈: 无额外占用空间-储存差值 |Min Stack with No extra space-Store as Difference

Problem description

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

The MinStack class:

  • Min Stack() initializes the stack object
  • void push(int val) pushes the element val onto stack
  • void pop() removes the element on the top of the stack
  • int top() get the top element of the stack
  • int getMin() retrieves the minimum element in the stack

Example:

Input: ["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

Output:
[null,null,null,null,-3,null,0,-2]

Normal method

The easy approach is to add a stack to store the minimum value of each element as the top of the stack in addition to the stack that stores the data.

class MinStack {
    private Deque stack;
    private Deque minStack;

    public MinStack() {
        stack = new LinkedList<>();
        minStack = new LinkedList<>();
        minStack.push(Integer.MAX_VALUE);
    }

    public void push(int val) {
        stack.push(val);
        minStack.push(Math.min(val, minStack.peek()));
    }

    public void pop() {
        stack.pop();
        minStack.pop();
    }

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

    public int getMin() {
        return minStack.peek();
    }
}

No extra space approach

What if we do not want(allowed) to use extra space to store the min value(minStack)?

Only store the difference in the stack! And store only one extra variable minValue.

Push to stack:
When the stack is empty, just store it, and assign it to minValue.

If the stack is not empty, we calculate the difference between the val and the minValue: diff=val-minValue, store it into the stack.

  • If the difference(diff) bigger than or equal to zero: diff>=0, then the entered value is greater than or equal to the minimum value in the stack, no need to update minValue.

  • If the difference(diff) is negative, then the entered value is less than minimum value in the stack, update the minValue.

Now let’s consider pop operation.

Pop from stack
When the stack is empty, operation fails.

If the stack is not empty.

  • If the peek value is non-negative. Then it doesn’t affect the minValue, just pop it.

  • If the peek value is negative. So we updated the minValue when pushing the value that make this peek difference, and the minValue is that val we want push to stack(call it new_minValue=val). So the old_minValue before push that element into stack should be old_minValue=new_minValue-diff.

top
Similar to pop.

If the stack is not empty:

  • If the peek value is non-negative. Then val=peekVall(diff)+minValue
  • If the peek value if negative. Then val=minValue.

min value
If the stack is not empty, return minValue.

It should be noticed that the differ operation may produce big integer that int can’t hold. Use Long or BigInteger instead.

Code as follows:

class MinStack {
    private Deque diffStack;
    private int minValue;

    public MinStack() {
        diffStack = new LinkedList<>();
        minValue = -1;
    }

    public void push(int val) {
        if (diffStack.isEmpty()) {
            diffStack.push(0L);
            minValue = val;
        } else {
            diffStack.push(Long.valueOf(val) - minValue);
            minValue = Math.min(minValue, val);
        }
    }

    public void pop() {
        Long diff = diffStack.pop();
        if (diff < 0) {
            minValue = (int) (minValue - diff);
        }
    }

    public int top() {
        Long diff = diffStack.peek();
        return diff >= 0 ? (int) (diff + minValue) : minValue;
    }

    public int getMin() {
        return diffStack.isEmpty() ? -1 : minValue;
    }
}

Original: https://www.cnblogs.com/liuzhch1/p/16403341.html
Author: liuzhch1
Title: LeetCode 155最小栈: 无额外占用空间-储存差值 |Min Stack with No extra space-Store as Difference

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/606682/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • 1.1学习计算机网络概述

    对应层次讲协议,上下层讲服务。 一. 1.发送方如何使数据达到对方的相应层次? 作为发送方,传输数据的过程中,要遵从网络体系结构的要求,即:层次和协议的集合。因此双方所采用的网络层…

    Linux 2023年6月6日
    0106
  • shell 配置文件节约空间

    shell 配置文件节约空间 sed 读取一个配置文件的的多个变量 Original: https://www.cnblogs.com/hshy/p/16451927.htmlAu…

    Linux 2023年5月28日
    089
  • 利用prometheus 客户端采集磁盘容量脚本

    点击查看代码 #!/bin/bash #date: 20220621 #author:bin >/tmp/node_dmz.txt >/tmp/node_err.txt…

    Linux 2023年6月14日
    0101
  • 你真的了解JAVA中对象和类、this、super和static关键字吗

    作者:小牛呼噜噜 | https://xiaoniuhululu.com计算机内功、JAVA底层、面试相关资料等更多精彩文章在公众号「小牛呼噜噜 」 Java对象究竟是什么? 创建…

    Linux 2023年6月6日
    0123
  • The remote debugger is older than this version of Visual Studio 2019, and Visual Studio is no longer compatible with it. Upgrade your remote debugger to match Visual Studio.

    之前一直使用VS2019来打包到Xbox上,但是这两天有一个项目,只能用2017部署,于是下载了vs2017,然后这个2017的项目顺利打包到Xbox,但是2019的项目却部署失败…

    Linux 2023年6月13日
    079
  • Redis 常用五种数据类型编码

    1.String 1.1 常用命令 (1)设置值 set key value [ex seconds] [px milliseconds] [nx|xx] set命令有几个选项: …

    Linux 2023年5月28日
    099
  • 微信小程序转uniapp

    微信小程序转uniapp 安装包 cnpm install miniprogram-to-uniapp -g 查看版本 wtu -V 转化执行 wtu -i 要转化的小程序目录 例…

    Linux 2023年6月7日
    097
  • Spring 4 集成 redis 实现缓存 一

    随着Web项目的复杂程度逐渐增加,可能会涉及诸如高并发、海量数据查询的的业务场景也逐渐增多;若频繁的操作数据库,会触发数据库的I/O瓶颈,因此需要加入缓存,尽量减少直接操作数据库的…

    Linux 2023年6月14日
    095
  • Spring事务(三)-事务失效场景

    有时候,我们明明在类或者方法上添加了 @Transactional注解,却发现方法并没有按事务处理。其实,以下场景会导致事务失效。 1、事务方法所在的类没有加载到Spring IO…

    Linux 2023年6月6日
    0100
  • LeetCode-补充题2. 圆环回原点问题

    题目来源 题目详情 圆环上有10个点,编号为0~9。从0点出发,每次可以逆时针和顺时针走一步,问走n步回到0点共有多少种走法。 输入: 2输出: 2解释:有2种方案。分别是0-&g…

    Linux 2023年6月7日
    0105
  • SSH免密登录

    SSH免密登录实现三步: 客户端生成公钥和私钥 上传公钥到服务端 SSH免密登录 (1) 客户端生成和公钥和私钥 ssh-keygen 一路回车即可,默认会在~/.ssh/目录下创…

    Linux 2023年6月7日
    0103
  • 聊聊简单又灵活的权限设计(RBAC)

    你:我看完能知道个啥?我:也就以下两点吧一. 了解基于 RBAC 思路的表设计二. 表数据在实际开发场景中是如何使用的你:我觉得那应该还有点干货吧我:我不要你觉得,我要我觉得 (͡…

    Linux 2023年6月14日
    0111
  • 系统初始化

    一般系统安装好后,按照自己习惯定义 csharp;gutter:true;</p> <h1>alias</h1> <p>echo &…

    Linux 2023年6月7日
    064
  • JAVA反射机制详解

    作者:小牛呼噜噜 | https://xiaoniuhululu.com计算机内功、JAVA底层、面试相关资料等更多精彩文章在公众号「小牛呼噜噜 」 何为反射? 实例的创建 .cl…

    Linux 2023年6月6日
    0155
  • redis数据结构附录

    引言 本次对上一次的数据结构知识进行补充,主要有redis数据结构的相关应用场景和内存相关知识 引用计数-内存 redis中的对象回收机制是采用引用计数的方式,首先我们可以通过re…

    Linux 2023年6月13日
    0100
  • 【原创】Linux虚拟化KVM-Qemu分析(五)之内存虚拟化

    背景 Read the fucking source code! –By 鲁迅 A picture is worth a thousand words. –…

    Linux 2023年6月8日
    082
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球