155.最小栈-python.md

题目

设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。

push(x) – 将元素 x 推入栈中。
pop() – 删除栈顶的元素。
top() – 获取栈顶元素。
getMin() – 检索栈中的最小元素。

示例:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2.
解法:

      该题比较简单,只需要在init内初始化一个列表和最小值,每次堆值和取值时判断一下是否是最小值即可,如果取走的是最小值,则遍历取出新的最小值。

示例
class MinStack:
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack = []
        self.min = None

    def push(self, x):
        """
        :type x: int
        :rtype: void
        """
        self.stack.append(x)
        if self.min == None or self.min > x:
            self.min = x

    def pop(self):
        """
        :rtype: void
        """
        # 栈堆为空
        if not self.stack:
            return None
        popitem = self.stack.pop()

        # 栈堆为空
        if not self.stack:
            self.min = None
            return popitem

        # 如果取出的值是最小值
        if popitem == self.min:
            self.min = self.stack[0]
            # 遍历找出新的最小值
            for i in self.stack:
                if i < self.min:
                    self.min = i
        return popitem
执行结果

执行结果

猜你喜欢

转载自blog.csdn.net/wangsiyu34567/article/details/82827536
今日推荐