leetcode 155. Min Stack(python)

333 阅读1分钟

描述

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

Implement the MinStack class:

  • MinStack() initializes the stack object.
  • void push(val) pushes the element val onto the stack.
  • void pop() removes the element on the top of the stack.
  • int top() gets the top element of the stack.
  • int getMin() retrieves the minimum element in the stack.

Example 1:

Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

Output
[null,null,null,null,-3,null,0,-2]

Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top();    // return 0
minStack.getMin(); // return -2	

Note:

-2^31 <= val <= 2^31 - 1
Methods pop, top and getMin operations will always be called on non-empty stacks.
At most 3 * 10^4 calls will be made to push, pop, top, and getMin.

解析

根据题意,就是实现各种操作的函数,基本都是对列表的操作,思路简单,不懂的重温 python 语法吧。

解答

class MinStack(object):


    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack = []
    def push(self, val):
        """
        :type val: int
        :rtype: None
        """
        self.stack.append(val)

    def pop(self):
        """
        :rtype: None
        """
        if self.stack:
            self.stack.pop(-1)

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

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

运行结果

Runtime: 616 ms, faster than 25.12% of Python online submissions for Min Stack.
Memory Usage: 16.9 MB, less than 89.88% of Python online submissions for Min Stack.

原题链接:leetcode.com/problems/mi…

您的支持是我最大的动力