Python 40ms solution


  • 0
    def __init__(self, iterator):
        """
        Initialize your data structure here.
        :type iterator: Iterator
        """
        self.iterator = iterator
        self.cache = []
        
    
    def peek(self):
        """
        Returns the next element in the iteration without advancing the iterator.
        :rtype: int
        """
        if not self.cache:
            self.cache.append(self.iterator.next())
        return self.cache[0]
    
        
    
    def next(self):
        """
        :rtype: int
        """
        if self.cache:
            return self.cache.pop(0)
        else:
            return self.iterator.next()
        
    
    def hasNext(self):
        """
        :rtype: bool
        """
        return len(self.cache) != 0 or self.iterator.hasNext()

  • 0
    A

    Why do you need a list for the cache? There can be only one element cached at a time.


Log in to reply
 

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