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
相关推荐
JieE2128 小时前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
金銀銅鐵13 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup1118 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0020 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵21 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 天前
Agent 流程编排
后端·python·agent
copyer_xyf1 天前
Agent RAG
后端·python·agent
copyer_xyf1 天前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf1 天前
Agent 记忆管理
后端·python·agent