Leetcode brushing record-155. Minimum stack

Insert picture description here

The difference between the minimum stack of this question and the conventional stack is that it
needs a function that can return the minimum value in constant time.
Considering that we need to be able to return the minimum value at any time, we need to
calculate the minimum value of the current time every time we enter an element. Value
Therefore, we need to record a min every time we push.
Therefore, it is easy to think that the data structure to record the min value is the same as the length of the original stack.
Therefore, prepare a list to store the minimum value when pushing.

class MinStack:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.realmin = None
        self.premin = None
        self.stack = []
        self.minstack = []
        self.stackdict = {}


    def push(self, x: int) -> None:
        self.stack.append(x)
        if self.minstack == []:
            self.minstack.append(x)
        elif self.minstack[-1] <= x:
            self.minstack.append(self.minstack[-1])
        else:
            self.minstack.append(x)



    def pop(self) -> None:
        self.minstack.pop(-1)
        return self.stack.pop(-1)#-1]#-1)
        #thisvalue = self.stack.pop()
        #self.stackdict[thisvalue] -= 1
        #if self.stackdict[thisvalue] == 0:
        #    del self.stackdict[thisvalue]


    def top(self) -> int:

        return self.stack[-1]


    def getMin(self) -> int:

        return self.minstack[-1]

Published 43 original articles · praised 14 · 20,000+ views

Guess you like

Origin blog.csdn.net/weixin_41545780/article/details/105463475