LeetCode刷题 (Python) | 155. Min Stack

LeetCode刷题 (Python) | 155. Min Stack

题目链接

https://oj.leetcode.com/problems/min-stack/

心得

题目的重点在于使用两个堆栈,一个堆栈stack保存用户数据,另一个堆栈minStack保存堆栈中的最小值。

AC代码

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

    def push(self, x):
        """ :type x: int :rtype: nothing """
        self.stack.append(x)
        if len(self.minStack) == 0 or x <= self.minStack[-1]:
            self.minStack.append(x)

    def pop(self):
        """ :rtype: nothing """
        if not self.isEmpty():
            if self.top() == self.minStack[-1]:
                self.minStack.pop()
            self.stack.pop()
        return

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

    def getMin(self):
        """ :rtype: int """
        if not self.isEmpty():
            return self.minStack[-1]

    def isEmpty(self):
        return len(self.stack) < 1


if __name__ == "__main__":
    minstack = MinStack()
    minstack.push(2)
    minstack.push(0)
    minstack.push(3)
    minstack.push(0)
    print(minstack.getMin())
    minstack.pop()
    print(minstack.getMin())
    minstack.pop()
    print(minstack.getMin())
    minstack.pop()
    print(minstack.getMin())

遗留问题

程序耗时大约120ms,仅打败了10%的python代码。不知道哪里还可以改进,希望有大神可以指点。

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