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)

大家都在看

  • rsync

    rsync是什么 rsync特性 1)可以镜像保存整个目录树和文件系统。 2)可以很容易做到保持原来文件的权限、时间、软硬连接等。 3)无需特殊权限即可安装。 4)快速:第一次同步…

    Linux 2023年6月6日
    093
  • Linux常用扩展

    目录 ~ ? * [] {} 1. ~ 代表当前用户的home目录 pwd ~$ /home/user/ ls ~$ a touch ~/b ls ~$ a b ~ 等于/home…

    Linux 2023年6月7日
    088
  • 2-第一个Django程序

    第一个Django程序 从本章节开始将通过实现一个投票应用程序,来让用户逐步的了解Django。这个程序由两步分组成: 公共站点,允许用户访问进行投票,和查看投票。 站点管理,允许…

    Linux 2023年6月7日
    0118
  • [云原生]Kubernetes-Pod控制器详解(第6章)

    一、Pod控制器介绍 二、ReplicaSet(RS) 三、Deployment(Deploy) 四、Horizontal Pod Autoscaler(HPA) 五、Daemon…

    Linux 2023年6月13日
    0126
  • JavaScript快速入门-06-函数

    6 函数 6.1 函数定义 函数可以封装语句,然后在任何地方、任何时间执行。JavaScript中的函数使用 function关键字声明,主要由 函数名、 函数参数和 函数体组成。…

    Linux 2023年6月7日
    0111
  • 分布式系统下的CAP定理

    本文参考EricBrewer博客加上自己的理解整理。 CAP定理又被成为布鲁尔定理,是加州大学计算机科学家埃里克·布鲁尔提出来的猜想,后来被证明成为分布式计算领域公认的定理。 CA…

    Linux 2023年6月13日
    093
  • 前端之jQuery快速入门

    一、jQuery 一款轻量级的JS框架。jQuery的核心JS文件才几十kb,不会影响页面加载速度。 丰富的DOM选择器,jQuery的选择器用起来很方便,比如要找到某个DOM对象…

    Linux 2023年6月14日
    097
  • redis主从复制

    Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件。 特性: 运行在内存中的数据集工作方式 支持多种数据结构 提供不同级别的磁盘持…

    Linux 2023年5月28日
    086
  • 解决关闭shell会话窗口则会发现ASP.NET Core应用也会被关闭问题

    统计了三种方法: 一、使用nohup命令即可 【最简单】 nohup dotnet xxxx.dll 【xxxx为应用名称】 一般会报:nohup: ignoring input …

    Linux 2023年6月8日
    0126
  • 学习linux(centos7)记录的笔记

    此随笔用于记录学习《linux鸟哥的私房菜》过程中1.遇到的问题及解决的过程 2.有必要记录的重要内容 3.对应书上操作的记录 开始于2021年6月18号 一个磁盘的分区通过格式化…

    Linux 2023年6月6日
    093
  • Ubuntu 18.04 LTS的网络经常变成问号导致网速很慢的解决办法

    问题描述: Ubuntu系统Gnome桌面顶部栏的网络图标经常变成了一个问号。期间不能打开网页,在终端里面ping公网有时能通但丢包严重,或者根本就不通,错误提示 Temporar…

    Linux 2023年5月27日
    0125
  • 【转】 一条 SQL 的执行过程详解

    MySQL 体系架构 – 连接池组件 1、负责与客户端的通信,是半双工模式,这就意味着某一固定时刻只能由客户端向服务器请求或者服务器向客户端发送数据,而不能同时进行。 …

    Linux 2023年6月13日
    0133
  • RPA纳税申报机器人

    bash;gutter:true;1、机器人开始工作2、机器人打开企业内部税务平台,自动下载报税底表3、机器人自动登录地方税务局,填写报税数据手工报税10分钟/3个表 VS 机器人…

    Linux 2023年6月7日
    083
  • MySQL——索引结构

    索引:用于快速查找数据。 索引是将数据的一些关键信息通过特定的数据结构存储到一片新的空间中,这样在文件查找的时候能快速找到。 mysql索引类型: B+TREE、HASH、R-TR…

    Linux 2023年6月7日
    0113
  • [ Shell ] 通过 Shell 脚本导出 GDSII/OASIS 文件

    常见的集成电路版图数据库文件格式有 GDSII 和 OASIS,virtuoso 提供了下面两个工具,可以用来通过命令行导出版图数据。 strmout (导出为 GDSII 格式)…

    Linux 2023年6月7日
    0131
  • 一文带你全面了解什么是颠覆时代的Web3.0未来互联网

    前言 大家还记得前段时间Meta公司,也就是FaceBook改名后的那家,CEO扎克伯格发的那张元宇宙自拍吗? 他没想到的是,随手的一张自拍却引来了群嘲,20年前的像素感,粗糙的人…

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