Python 1 line of code for each definition and only using 1 stack (feedback welcome)


  • -1
    S

    The code is slightly sped up by computing self.getMin() once in 'push' vs. 3 times.

    class MinStack(object):
        def __init__(self):
            self.stack = []
    
        def push(self, x):
            self.stack.append((x, x if self.getMin() is None or x < self.getMin() else self.getMin()))
    
        def pop(self):
            self.stack.pop()
    
        def top(self):
            return None if not self.stack else self.stack[-1][0]
    
        def getMin(self):
            return None if not self.stack else self.stack[-1][1]

  • 0
    S

    these down votes without any guidance for improvement are quite discouraging :(


  • 0

    = = this is essentially the same with two stacks, man.
    but it consumes more memory.


Log in to reply
 

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