leetcode 155. Min Stack 的思路与python实现

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
getMin() – Retrieve the minimum element in the stack.

思路

栈的特点,先进先出。一个栈不会从中间取走值,只能从顶部放入和取走。
入栈一个值的时候需要更新最小值,最小值会变小或者不变。而出栈的时候,最小值则会恢复到它上面的值进来之前的状态。

解决方式

肯定要一个【主栈】记录值。
另外使用另一个栈【最小值栈】来记录最小值,栈顶即为当前最小值。
每次【主栈】入栈,【最小值栈】也入栈,对比新值与当前栈顶值,入小的那一个。
每次【主栈】出栈,【最小值栈】也出栈。
getMin则返回【最小值栈】栈顶值。

代码

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

    def push(self, x: int) -> None:
        self.stack.append(x)
        if len(self.minstack) == 0 or x < self.minstack[-1]:
            self.minstack.append(x)
        else:
            self.minstack.append(self.minstack[-1])

    def pop(self) -> None:
        self.stack.pop(-1)
        self.minstack.pop(-1)

    def top(self) -> int:
        return self.stack[-1]

    def getMin(self) -> int:
        return self.minstack[-1]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值