Min Stack Python


  • -2
    F
    class MinStack:
    def __init__(self):
        self.onestack = []
        self.anotherstack = []
     
    # Push element x onto stack    
    def push(self, x):
        # for onestack, just append x
        self.onestack.append(x)
        # for anotherstack, pull in the ones only less than the ones already in the stack
        if self.anotherstack == []:
            self.anotherstack.append(x)
        else:
            if x < min(self.anotherstack):
                self.anotherstack.append(x)
        
    # Remove the element on top of the stack    
    def pop(self):            
        self.onestack.pop()
    
    # Get the top element    
    def top(self):
        last_index = len(self.onestack) - 1
        return self.onestack[last_index]
    
    # Retrieve the minimum in the stack    
    def getMin(self):
        last_index = len(self.anotherstack) - 1
        return self.anotherstack[last_index]
    

    I cannot get passed by the test. But it seems ok on my local machine running OSX. Any input, guys?


  • 1
    V

    You don't remove element in anotherstack while pop onestack.


Log in to reply
 

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