281.Zigzag Iterator

Tags: [data_structure], [queue], [iterator]

Com: {fb}

Link: https://leetcode.com/problems/zigzag-iterator/\#/description

Given two 1d vectors, implement an iterator to return their elements alternately.

For example, given two 1d vectors:

v1 = [1, 2]
v2 = [3, 4, 5, 6]

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:[1, 3, 2, 4, 5, 6].

Follow up: What if you are given k1d vectors? How well can your code be extended to such cases?

Clarification for the follow up question -Update (2015-09-18):
The "Zigzag" order is not clearly defined and is ambiguous fork > 2cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic". For example, given the following input:

[1,2,3]
[4,5,6,7]
[8,9]

It should return[1,4,8,2,5,9,3,6,7].


Solution: Queue

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]
        """
        queue_1 = deque(v1)
        queue_2 = deque(v2)
        self.main_queue = deque()
        if queue_1:
            self.main_queue.append(queue_1)
        if queue_2:
            self.main_queue.append(queue_2)


    def next(self):
        """
        :rtype: int
        """
        q = self.main_queue.popleft()
        val = q.popleft()
        if q:
            self.main_queue.append(q)

        return val


    def hasNext(self):
        """
        :rtype: bool
        """
        return len(self.main_queue) > 0


# Your ZigzagIterator object will be instantiated and called as such:
# i, v = ZigzagIterator(v1, v2), []
# while i.hasNext(): v.append(i.next())

Note:

  • Time complexity of initialization = O(n), n is the total number of elements.
  • Time complexity of next = O(1).
  • Time complexity of hasNext = O(1).

results matching ""

    No results matching ""