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
相关推荐
高洁015 分钟前
智能博弈背景下中国AI国防建设的战略价值
人工智能·python·深度学习·django·tornado
淡海水10 分钟前
02-04-原理篇-GC Roots与对象图遍历
算法·unity·c#·图·gc·遍历·roots
han688912 分钟前
selenium之实战
笔记·python·selenium·测试工具·自动化
ClickHouseDB13 分钟前
ClickHouse 大规模 OpenTelemetry 数据接入架构的可靠性演进
算法
yumgpkpm18 分钟前
(CDH 7)CDP Private Cloud Base 7.3.1 → Acceldata ODP 3.3.6.4 引擎迁移风险评估表
服务器·人工智能·hadoop·python·华为·zookeeper·hbase
Shaoshing20 分钟前
BHU 润石工作室 251019自建赛题解
算法
刘天远21 分钟前
Agent成本核算实现:事件表、状态分布与Python归集
前端·数据库·人工智能·python
Python图像识别32 分钟前
40-【2027毕设】YOLO11面部口罩检测识别系统 - Python完整源码+PyQt5界面+训练模型+数据集
python·qt·课程设计
赵大仁36 分钟前
开源清单怎么维护才不烂掉?GitHub Actions 每周查死链 + 软 404 检测实录
python·ci/cd·自动化·开源项目·踩坑·github actions·json schema
玩AI的奶茶38 分钟前
24GB 显存能跑多大的模型?参数量、精度与显存占用对照表
人工智能·python·算法·ai·aigc·gpu算力·算力租赁