[LeetCode] 155. Min Stack

版权声明:转载请和我说。 https://blog.csdn.net/u010929628/article/details/89636648

题目内容

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.

题目思路

这道题的考点在于建立一个最小栈来获取每次的最小值。也就是当一个新的元素入栈时,如果最小栈为空则把这个元素放入最小栈,否则将把这个元素和最小栈元素最小值进行比较后,选择更小的那个放入栈中。


程序代码

class MinStack(object):

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

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

    def pop(self):
        """
        :rtype: None
        """
        tmp=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]
        


# 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/u010929628/article/details/89636648