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]))
   = sum(map(len, [v1, v2]))
        def next(self):
            :rtype: int
            deq = self.deq
            left = deq.popleft()
                value = 
            except StopIteration:
   -= 1
            if != 0:
            return value
        def hasNext(self):
            :rtype: bool
            return > 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.