[25] 用 python 刷 Leetcode: 155 min-stack

原始题目

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Implement the MinStack class:

  • MinStack() initializes the stack object.
  • void push(int val) pushes the element val onto the stack.
  • void pop() removes the element on the top of the stack.
  • int top() gets the top element of the stack.
  • int getMin() retrieves the minimum element in the stack.

Example 1:

Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

Output
[null,null,null,null,-3,null,0,-2]

Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top();    // return 0
minStack.getMin(); // return -2

题目分析

设计具有 push, pop, top 操作,并能在常数时间 O(n) 内查询到最小元素的堆叠

解题过程

  1. 建立一个 list min_stack纪录堆叠最小值
  2. 建立stack list 作为堆叠纪录
  3. push:把值放进堆叠後面,如果该值小於等於 min_stack 堆叠的最後一笔资料,则一并加入 min_stack 堆叠
  4. pop:从 stack 移除最上面一笔值,如果该值等於 min_stack 最後一笔,一并从堆叠移除
  5. top:取得堆叠最上面一个元素stack[-1]
  6. getMin:取得最小值,也就是 min_stack 的最後一个元素min_stack[-1]
class MinStack:
    def __init__(self):
        self.stack = []
        self.min_stack = []

    def push(self, val: int) -> None:
        self.stack.append(val)
        if not self.min_stack or val <= self.min_stack[-1]: 
            self.min_stack.append(val)

    def pop(self) -> None:
        if self.stack.pop() == self.min_stack[-1]:
            self.min_stack.pop()
    
    def top(self) -> int:
        return self.stack[-1]
    
    def getMin(self) -> int:
        return self.min_stack[-1]

# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()

结果

result


<<:  网页编排Grid-30天学会HTML+CSS,制作精美网站

>>:  JavaScript Day 30. 关於 JavaScript 中的 This

[day30] Line购物机器人 小总结与感想

今天的文章分为两部分,一个是今天做完的部分修改,一部份是参赛感想 今日的品质更新 & 逻辑修...

Flutter体验 Day 23-WebSocket

WebSocket 前端对於WebSocket这项技术应该不陌生,以往会需要使用轮询的方式更新资料,...

Day 08:原则、设计模式、架构

前言 接下来要介绍的东西并不是学什麽工具, 而是怎麽把我们已经会的程序语言写得更有系统, 来达到高效...

VPC (一)

VPC介绍 介绍完关於GCP使用这权限设置,再来需要了解的是GCP中的网路层,在网路部分可以说是极其...

爬虫怎麽爬 从零开始的爬虫自学 DAY12 python列表进阶篇

前言 各位早安,书接上回我们练习了一些基础list用法跟一些技巧,今天我们要来深入探讨list更多能...