力扣-155-最小栈

问题:

# 设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。 
#
#
# push(x) —— 将元素 x 推入栈中。
# pop() —— 删除栈顶的元素。
# top() —— 获取栈顶元素。
# getMin() —— 检索栈中的最小元素。

方法:双栈结构(一个存储数据,一个存储最小值)

# leetcode submit region begin(Prohibit modification and deletion)
class MinStack(object):

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

    def push(self, val):
        """
        :type val: int
        :rtype: None
        """
        self.stack.append(val)
        self.min_stack.append(min(val, self.min_stack[-1]))

    def pop(self):
        """
        :rtype: None
        """
        self.stack.pop()
        self.min_stack.pop()

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

    def getMin(self):
        """
        :rtype: int
        """
        return self.min_stack[-1]
时刻记着自己要成为什么样的人!
原文地址:https://www.cnblogs.com/demo-deng/p/14775061.html