• ㊗️
• 大家
• offer
• 多多！

## Problem

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

Example:

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


What if you are given k 1d vectors? How well can your code be extended to such cases?

Clarification for the follow up question: The “Zigzag” order is not clearly defined and is ambiguous for k > 2 cases. If “Zigzag” does not look right to you, replace “Zigzag” with “Cyclic”. For example:

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

Output: [1,4,8,2,5,9,3,6,7].****


## Code

public class ZigzagIterator {
Iterator<Integer> iter1;
Iterator<Integer> iter2;
Iterator<Integer> temp;
public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
iter1 = v2.iterator();
iter2 = v1.iterator();
}

public int next() {
temp = iter1;
iter1 = iter2;
iter2 = temp;
if(!iter1.hasNext()){
iter1 = iter2;
}

return iter1.next();
}

public boolean hasNext() {
return iter1.hasNext() || iter2.hasNext();
}
}

/**
* Your ZigzagIterator object will be instantiated and called as such:
* ZigzagIterator i = new ZigzagIterator(v1, v2);
* while (i.hasNext()) v[f()] = i.next();
*/

• 把需要的 index 放在 queue 中，这样复杂度为 O(1)
class ZigzagIterator:
def __init__(self, v1: List[int], v2: List[int]):
self.arrs = [v1, v2]
self.queue = deque()
for i in range(0, 2):
if len(self.arrs[i]) > 0:
self.queue.append((i, 0))

def next(self) -> int:
if self.queue:
arr_index, elem_index = self.queue.popleft()
next_elem_index = elem_index + 1
if next_elem_index < len(self.arrs[arr_index]):
self.queue.append((arr_index, next_elem_index))

return self.arrs[arr_index][elem_index]

raise Exception

def hasNext(self) -> bool:
return len(self.queue) > 0