python stack 简约栈

LeetCode 115 Min Stack

思想:
利用python中内置的append函数压栈
用pop函数出栈
stack[-1]为右一栈顶元素
min函数求栈中最小值

class MinStack(object):

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

    def push(self, x):
        """
        :type x: int
        :rtype: void
        """
        self.stack.append(x)

    def pop(self):
        """
        :rtype: void
        """
        self.stack.pop()

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

    def getMin(self):
        """
        :rtype: int
        """
        return min(self.stack)


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

猜你喜欢

转载自blog.csdn.net/ZHANGWENJUAN1995/article/details/84570197