Python O(1) Solution


  • 0
    D

    '''
    class MinStack(object):

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.st=[]
        self.lessSt=[]
        self.mi=None
        
    def push(self, x):
        """
        :type x: int
        :rtype: void
        """
        if len(self.st) == 0:
            self.mi = x
        if self.mi == None or x<=self.mi:
            self.mi = x
            self.lessSt.append(x)
        self.st.append(x)
        
    def pop(self):
        """
        :rtype: void
        """
        if len(self.st) == 0 or len(self.lessSt) == 0:
            return None
        poped = self.st.pop()
        if poped == self.lessSt[-1]:
            self.lessSt.pop()
            if len(self.lessSt) == 0:
                self.mi = None
            else:
                self.mi = self.lessSt[-1]
    
    def top(self):
        """
        :rtype: int
        """
        if len(self.st) == 0:
            return None
        else:
            return self.st[-1]
        
    def getMin(self):
        """
        :rtype: int
        """
        if len(self.lessSt) == 0:
            return None
        else:
            return self.lessSt[-1]
    

    '''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.