美文网首页
leetcode 155 python 最小栈

leetcode 155 python 最小栈

作者: 慧鑫coming | 来源:发表于2019-01-31 14:42 被阅读0次

传送门

题目要求

设计一个支持 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.

思路一

利用元组,每次压栈操作,都记录当前栈内最小元素

→_→ talk is cheap, show me the code

class MinStack:

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

    def push(self, x):
        """
        :type x: int
        :rtype: void
        """
        if not self.stack or self.stack[-1][0] >= x:
            self.stack.append((x,x))
        else:
            self.stack.append((self.stack[-1][0], x))

    def pop(self):
        """
        :rtype: void
        """
        self.stack.pop()

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

    def getMin(self):
        """
        :rtype: int
        """
        return self.stack[-1][0]

相关文章

  • LeetCode-155-最小栈

    LeetCode-155-最小栈 155. 最小栈[https://leetcode-cn.com/problem...

  • leetcode 155 python 最小栈

    传送门 题目要求 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。 push(x...

  • LeetCode 155. 最小栈 | Python

    155. 最小栈 题目来源:https://leetcode-cn.com/problems/min-stack ...

  • LeetCode:155. 最小栈

    问题链接 155. 最小栈[https://leetcode-cn.com/problems/min-stack/...

  • 2.栈(二)

    题目汇总:https://leetcode-cn.com/tag/stack/155. 最小栈简单[✔]173. ...

  • 最小栈(LeetCode 155)

    题目: 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。 示例: 方法: 使用一...

  • 155. 最小栈

    155. 最小栈[https://leetcode.cn/problems/min-stack/] 设计一个支持 ...

  • 155. 最小栈

    题目地址(155. 最小栈) https://leetcode.cn/problems/min-stack/[ht...

  • LeetCode刷题笔记(三)栈与队列

    三. 栈与队列 python中的栈直接用list实现,队列用deque,需要导入外部包。 155. 最小栈 题目:...

  • LeetCode 155. 最小栈

    题目描述 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。 push(x) --...

网友评论

      本文标题:leetcode 155 python 最小栈

      本文链接:https://www.haomeiwen.com/subject/emwksqtx.html