DAILY DOCDAILY DOC
Rust
Node
Notes
Ubuntu
Leetcode
  • it-tools
  • excalidraw
  • linux-command
Rust
Node
Notes
Ubuntu
Leetcode
  • it-tools
  • excalidraw
  • linux-command
  • Array

    • 数组
    • 二分查找
    • moveZeros
  • Dynamic-programming

    • 动态规划
  • 刷题指南
  • String

    • 字符串
  • bitwise-operator

    • 位运算符
  • heap
  • history

    • [1014] 最佳观光组合
    • [1022] 从根到叶的二进制数之和
    • [104] 二叉树的最大深度
    • [11] 盛最多水的容器
    • [110] 平衡二叉树
    • [1227] 飞机座位分配概率
    • [129] 求根节点到叶节点数字之和
    • [1306] 跳跃游戏 III
    • [148] 排序链表
    • 155.最小栈
    • [165] 比较版本号
    • 1763. 最长的美好子字符串
    • [1870] 准时到达的列车最小时速
    • [199] 二叉树的右视图
    • [21] 合并两个有序链表
    • 215.数组中的第 k 个最大元素
    • [2306] 公司命名
    • [234] 回文链表
    • [2516] 每种字符至少取 K 个
    • [316] 去除重复字母
    • [3171] 找到按位或最接近 K 的子数组
    • [322] 零钱兑换
    • [41] 缺失的第一个正数
    • [44] 通配符匹配
    • [494] 目标和
    • [509] 斐波那契数
    • [518] 零钱兑换 II
    • [62] 不同路径
    • [676] 实现一个魔法字典
    • 70 爬楼梯
    • [718] 最长重复子数组
    • [78] 子集
    • [82] 删除排序链表中的重复元素 II
    • [871] 最低加油次数
    • [88] 合并两个有序数组
    • [887] 鸡蛋掉落
    • 958.二叉树的完全性检验
    • [98] 验证二叉搜索树
    • [983] 最低票价
    • leetcode practice
    • 约瑟夫问题
    • 移除重复节点
  • linked-list

    • 706. 设计哈希映射
    • 链表
  • stack

    • stack
  • tree

    • Tree Traversal
    • 二叉树的最近公共祖先
    • 二叉树
    • 题目
  • leetCode 刷题
  • 回溯
  • 排序算法

155.最小栈

details
class MinStack {
    constructor() {
        this.stack = [];
        this.minStack = [];
    }

    push(val) {
        this.stack.push(val);
        // If the minStack is empty or the new value is less than or equal to the current minimum, push it onto the minStack
        if (this.minStack.length === 0 || val <= this.getMin()) {
            this.minStack.push(val);
        }
    }

    pop() {
        // If the popped value is the same as the current minimum, pop it from the minStack as well
        if (this.stack.pop() === this.getMin()) {
            this.minStack.pop();
        }
    }

    top() {
        return this.stack.at(-1);
    }

    getMin() {
        return this.minStack.at(-1);
    }
}

// 测试用例
let minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
console.log(minStack.getMin()); // 返回 -3
minStack.pop();
console.log(minStack.top()); // 返回 0
console.log(minStack.getMin()); // 返回 -2

解释

  1. 构造函数 MinStack:

    • this.stack 用于存储实际的栈元素。
    • this.minStack 用于存储最小值的辅助栈。
  2. push(val) 方法:

    • 将 val 压入 stack。
    • 如果 minStack 为空或 val 小于等于当前的最小值,将 val 压入 minStack。
  3. pop() 方法:

    • 如果弹出的元素是当前的最小值,也将其从 minStack 中弹出。
  4. top() 方法:

    • 返回 stack 栈顶的元素。
  5. getMin() 方法:

    • 返回 minStack 栈顶的元素,即当前的最小值。

复杂度分析

时间复杂度:

  • 所有操作(push, pop, top, getMin)都是 O(1) 的时间复杂度,因为辅助栈操作与主栈同步。

空间复杂度:

  • O(n),其中 n 是栈中的元素个数。最坏情况下,minStack 中的元素个数与 stack 中的元素个数相同。
Last Updated:
Contributors: rosendo
Prev
[148] 排序链表
Next
[165] 比较版本号