leetcode 面试题 03.02. 栈的最小值 python

leetcode 面试题 03.02. 栈的最小值

题目描述

在这里插入图片描述

题解

思路:
栈的特点:先进后出,在python中使用List模拟。
pop和push都很简单
主要是可以随时返回最小值,不能简单的只用一个变量记录最小值,因为一旦最小值被pop,那么上一个最小值,我们就不知道了…

所以要再用一个栈随时记录最小值,当数据栈有数据pop时,最小值栈也跟着pop

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

    def push(self, x: int) -> None:
        if self.stack and x >= self.mins[-1]:
            self.stack.append(x)
            self.mins.append(self.mins[-1])
        else:
            self.stack.append(x)
            self.mins.append(x)

    def pop(self) -> None:
        num = self.stack.pop()
        self.mins.pop()
        return num

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

    def getMin(self) -> int:
        return self.mins[-1]
发布了28 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/xxx_gt/article/details/104991530