32ms Python Solution beats 98.4 %


  • 0
    B

    class Queue(object):
    def init(self):
    """
    initialize your data structure here.
    """
    self.s1, self.s2 = [], []

    def push(self, x):
        """
        :type x: int
        :rtype: nothing
        """
        l1 = len(self.s1)
        for i in range(l1):
            self.s2.append(self.s1.pop())
        
        self.s1.append(x)
        
        for i in range(len(self.s2)):
            self.s1.append(self.s2.pop())
            
        
        
        
        
    
    def pop(self):
        """
        :rtype: nothing
        """
        if len(self.s1) == 0:
            return
        self.s1.pop()
        
    
    def peek(self):
        """
        :rtype: int
        """
        if len(self.s1) == 0:
            return
        return self.s1[len(self.s1) - 1]
        
    
    def empty(self):
        """
        :rtype: bool
        """
        if len(self.s1) == 0:
            return True
        return False

  • 1
    N

    Just a suggestion, for empty you can cut down the code by simply having: return len(self.s1) == 0. Also I would suggest using if self.empty() instead of if len(self.s1) == 0 in the other functions


Log in to reply
 

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