Python for k vector using iterator O(k) space


  • 1
    from collections import deque
    class ZigzagIterator(object):
    
        def __init__(self, v1, v2):
            """
            Initialize your data structure here.
            :type v1: List[int]
            :type v2: List[int]
            """
            self.deq = deque(map(iter, [v1, v2]))
            self.total = sum(map(len, [v1, v2]))
    
        def next(self):
            """
            :rtype: int
            """
            deq = self.deq
            left = deq.popleft()
            try:
                value = left.next() 
            except StopIteration:
                return self.next()
            self.total -= 1
            if self.total != 0:
                deq.append(left)
            return value
    
        def hasNext(self):
            """
            :rtype: bool
            """
            return self.total > 0
    

  • 0

    @jedihy Thanks for this delicate solution, I've never thought the way using except like this, would you mind mentioning some extra use case to help me expand the knowledge of this area?


  • 0

    Ohh, I don't even remember how I implemented it like this. Anyway, you can read document of python to know how to use iterator.


Log in to reply
 

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