155.最小栈

难度:简单
题目描述:
155.最小栈_第1张图片
思路总结:这瞎J8做的,回头还需要重做,看下list中的pop方法是怎么实现的,还有min方法的源码。

题解一:

class MinStack:

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

    def push(self, x: int) -> None:
        self.data.append(x)

    def pop(self) -> None:
        self.data.pop()

    def top(self) -> int:
        return self.data[-1]

    def getMin(self) -> int:
        return min(self.data)


# 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()

题解一结果:
在这里插入图片描述
题解二:(同步栈)
这题的要点是返回栈内最小值,这个解法,巧用同步栈,保留从栈底到当前元素的最小值。

class MinStack:

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

    def push(self, x: int) -> None:
        self.data.append(x)
        if not self.helper or x < self.helper[-1]:
            self.helper.append(x)
        else:
            self.helper.append(self.helper[-1])

    def pop(self) -> None:
        self.data.pop()
        self.helper.pop()

    def top(self) -> int:
        return self.data[-1]

    def getMin(self) -> int:
        return self.helper[-1]

题解二结果:
在这里插入图片描述

你可能感兴趣的:(朱滕威的面试之路)