【LeetCode】面试题30. 包含min函数的栈

题目:

思路:

空间换时间,关键在于pop操作后怎么保证min的正确性。因为要求min、push、pop的时间复杂度都是O(1),所以都不能进行排序操作。利用辅助空间,记录当前栈顶的最小值。一种是辅助空间和栈相同大小,比如栈内元素3、4、1、2、5,辅助空间为3、3、1、1、1,可以看到辅助空间有很多重复元素。可以简化一下辅助空间成3、1,注意相同最小元素要重复记录。

代码:

Python

class MinStack(object):

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

    def push(self, x):
        """
        :type x: int
        :rtype: None
        """
        # self.A.append(x)
        # if not self.B or x < self.B[-1]:
        #     self.B.append(x)
        # else:
        #     self.B.append(self.B[-1])
        self.A.append(x)
        if not self.B or x<= self.B[-1]:
            self.B.append(x)

    def pop(self):
        """
        :rtype: None
        """
        # self.A.pop()
        # self.B.pop()
        if self.A.pop() == self.B[-1]:
            self.B.pop()

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

    def min(self):
        """
        :rtype: int
        """
        return self.B[-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.min()

相关问题

posted @ 2020-06-09 10:16  一只背影  阅读(123)  评论(0编辑  收藏  举报