[leetcode] Min Stack @ Python

原题地址:https://oj.leetcode.com/problems/min-stack/

解题思路:开辟两个栈,一个栈是普通的栈,一个栈用来维护最小值的队列。

代码:

class MinStack:
    # @param x, an integer
    def __init__(self):
        self.stack1 = []
        self.stack2 = []
    # @return an integer
    def push(self, x):
        self.stack1.append(x)
        if len(self.stack2) == 0 or x <= self.stack2[-1]:
            self.stack2.append(x)

    # @return nothing
    def pop(self):
        top = self.stack1[-1]
        self.stack1.pop()
        if top == self.stack2[-1]:
            self.stack2.pop()
        
    # @return an integer
    def top(self):
        return self.stack1[-1]

    # @return an integer
    def getMin(self):
        return self.stack2[-1]

 

    原文作者:南郭子綦
    原文地址: https://www.cnblogs.com/zuoyuan/p/4091870.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞