leetcode__最小栈__python

解题思路:

栈的功能的实现,在实现的过程中维持一个最小值的变量即可。

具体代码如下:

class MinStack:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.data = []
        self.min = '#'
        self.top_val = '#'
        

    def push(self, x: int) -> None:
        self.data.append(x)
        self.top_val = x
        if self.min == '#':
            self.min = x
        else:
            self.min = min(self.min, x)

    def pop(self) -> None:
        if len(self.data) == 0:
            return False
        self.data = self.data[:-1]
        if self.data:
            self.top_val = self.data[-1]
            self.min = min(self.data)
        else:
            self.min = '#'
            self.top_val = '#'

    def top(self) -> int:
        return self.top_val

    def getMin(self) -> int:
        return self.min


# 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()

你可能感兴趣的:(leetcode,python)