LeetCode:155.最小栈

python 复制代码
class MinStack(object):

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack = []
        

    def push(self, x):
        """
        :type x: int
        :rtype: void
        """
        if not self.stack:
            self.stack.append((x, x))
        else:
            self.stack.append((x, min(x, self.stack[-1][1])))
        

    def pop(self):
        """
        :rtype: void
        """
        self.stack.pop()
        

    def top(self):
        """
        :rtype: int
        """
        return self.stack[-1][0]

解释

  • __init__: 初始化一个空栈,这里使用列表self.stack来存储栈元素。但不同于常规栈,这里的栈元素是一个元组(x, min_val),其中x是压入栈的原始值,min_val是到目前为止栈中的最小值。
  • push: 当压入一个新元素x时,它首先检查栈是否为空。如果栈为空,则直接压入(x, x)(因为此时x就是最小值)。如果栈不为空,则压入(x, min(x, self.stack[-1][1])),其中self.stack[-1][1]是栈顶元素对应的当前最小值。
  • pop: 弹出栈顶元素,即self.stack.pop()
  • top: 返回栈顶元素的原始值,即self.stack[-1][0]

举例

假设我们按照以下顺序对MinStack进行操作:

  1. 初始化一个MinStack对象。
  2. 使用push方法压入元素3。
  3. 使用push方法压入元素2。
  4. 使用push方法压入元素5。
  5. 调用top方法查看栈顶元素(应返回5)。
  6. 调用getMin方法(注意:虽然原代码中没有getMin方法,但根据类的设计,我们可以假设这个方法返回栈中的最小值,即返回self.stack[-1][1])。
  7. 使用pop方法弹出栈顶元素。
  8. 再次调用top方法查看栈顶元素(应返回2)。

下面是相应的Python代码示例(包括假设的getMin方法):

python 复制代码
class MinStack(object):
    # ...(省略了已给出的__init__、push、pop和top方法)

    def getMin(self):
        """
        :rtype: int
        """
        return self.stack[-1][1] if self.stack else None

# 使用示例
stack = MinStack()
stack.push(3)
stack.push(2)
stack.push(5)
print(stack.top())  # 输出: 5
print(stack.getMin())  # 输出: 2
stack.pop()
print(stack.top())  # 输出: 2
相关推荐
wabs666几秒前
关于二叉树【力扣101.对称二叉树的思考】
数据结构·c++·算法·leetcode·二叉树
绘梨衣5478 分钟前
PDF跨页表格处理方案(极简落地版 + 工具对比)
python·rag
实验室管理云平台15 分钟前
北京盛元广通推疾控中心实验室管理系统,提升检测效率
数据库·python
6Hzlia19 分钟前
【Classic 150 刷题计划】 LeetCode 228. 汇总区间 | C++ 双游标区间扫描与 to_string 规范
c++·算法·leetcode
玫幽倩38 分钟前
2026第二届湾区杯网络安全大赛决赛(AI专项赛道静态题wp)
pytorch·python·ai·agent·ctf·rag·湾区杯
TechWayfarer40 分钟前
IP地址查询之后:如何在请求抵达前识别风险
python·tcp/ip·网络安全
专注于ai算法的踩坑小达人1 小时前
TabFM(Google Tabular Foundation Model)完整部署手册(PyTorch GPU版)
人工智能·python
玖玥拾1 小时前
LeetCode 383 赎金信
算法·leetcode
特创数字科技1 小时前
公文Word一键批量排版工具|批量统一公文标准格式,办公自动化桌面小工具
前端·python
维克兜率天1 小时前
5.3 宏观因子:抬头看天
笔记·python·深度学习·算法·量化