美文网首页
155. 最小栈(easy)

155. 最小栈(easy)

作者: genggejianyi | 来源:发表于2019-06-13 22:08 被阅读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.

  • show the code:
class MinStack(object):

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

    def push(self, x):
        """
        :type x: int
        :rtype: None
        """
        self.stack.append(x)
        if not self.minstack:
            self.minstack.append(x)
        elif self.minstack[-1] < x:
            self.minstack.append(self.minstack[-1])
        else:
            self.minstack.append(x)

    def pop(self):
        """
        :rtype: None
        """
        if not self.stack:
            return False
        self.stack.pop()
        self.minstack.pop()

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

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


# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
  • 此题的关键在于设计一个辅助栈,其中的数据栈为stack,辅助栈为minstack,辅助栈用来存储当前的最小值。
  • 因为需要保持数据栈与辅助栈元素数量一致,因此在新进来一个元素x时,若x<minstack[-1]那么minstack.append(x)反之辅助栈再插入一个栈顶元素。
  • 其次删除栈顶元素时需保持数据栈与辅助栈一致。
  • 因为两个栈内元素数量保持一致,所以弹出元素后寻找最小值也可以在O(1)时间内找到,即minstack[-1]即可。

相关文章

  • 155. 最小栈(easy)

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

  • LeetCode-155-最小栈

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

  • 栈 问题

    155. 最小栈 常数时间内检索最小元素 使用一个辅助栈,与元素栈同步插入与删除,用于存储与每个元素对应的最小值。...

  • LeetCode:最小栈

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

  • LeetCode 155. 最小栈 | Python

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

  • LeetCode:155. 最小栈

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

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

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

  • 2.栈(二)

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

  • LeetCodeDay24 —— 最小栈

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

  • 155. 最小栈

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

网友评论

      本文标题:155. 最小栈(easy)

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