LeetCode 155. 最小栈

题目

设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。

push(x) -- 将元素 x 推入栈中。
pop() -- 删除栈顶的元素。
top() -- 获取栈顶元素。
getMin() -- 检索栈中的最小元素。

示例:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2.

解题思路

添加一个minIndex

class MinStack:

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


    def push(self, x: int) -> None:
        self.list.append(x)
        if len(self.list) > 0 and x < self.list[self.minIndex]:
            self.minIndex = self.list.index(x)
            # print("change: " + str(self.minIndex) + str(x))


    def pop(self) -> None:
        popNum = self.list.pop()
        if self.minIndex == (len(self.list)):
            # print("change: " + str(self.minIndex))
            self.minIndex = 0 if len(self.list) <=0 else self.list.index(min(self.list))
        return popNum


    def top(self) -> int:
        return None if len(self.list) <= 0 else self.list[-1]

    def getMin(self) -> int:
        # print("getMin: " + str(self.minIndex))
        return None if len(self.list) <= 0 else self.list[self.minIndex]

Github:https://github.com/freesan44/LeetCode

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容