155. 最小栈

  1. [题目链接](155. 最小栈 - 力扣(LeetCode))

  2. 解题思路:一个栈用来存储数据(数据栈),另一个栈用来放当前的最小值(最小栈)。

    • 当前最小值是什么?push一个数x,如果最小栈不为空,且最小栈栈顶元素小于x,那么接着push最小栈栈顶元素;否则push当前的x
    • pop时,两个栈同时pop即可
  3. 代码

    
    class MinStack:
    
        def __init__(self):
            self.data_st = []
            self.min_st = []
    
        def push(self, val: int) -> None:
            self.data_st.append(val)
            if self.min_st and self.min_st[-1] <= val:
                self.min_st.append(self.min_st[-1])
            else:
                self.min_st.append(val)
        def pop(self) -> None:
            self.data_st.pop()
            self.min_st.pop()
    
        def top(self) -> int:
            return self.data_st[-1]
    
        def getMin(self) -> int:
            return self.min_st[-1]
    
posted @ 2025-01-09 09:22  ouyangxx  阅读(21)  评论(0)    收藏  举报