Zigzag Iterator
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 k 1d vectors? How well can your code be extended to such cases?
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, 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]
.
分析
这种题的通用解法就是用一个Queue来装所有iterator, next()的时候,pop一个iterator, 取对应iterator.next()
, 如果之后iterator.hasNext()
再把该iterator push回到Queue中。
关键就是Queue中所存在的iterator必须hasNext(),所有写Constructor时也要注意。
复杂度
time: O(n), space: O(n)
代码
public class ZigzagIterator {
Queue<Iterator<Integer>> q;
public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
q = new LinkedList<Iterator<Integer>>();
Iterator<Integer> it1 = v1.iterator();
Iterator<Integer> it2 = v2.iterator();
// 保证Queue中的Iterator hasNext().
if (it1.hasNext())
q.add(it1);
if (it2.hasNext())
q.add(it2);
}
public int next() {
Iterator<Integer> it = q.remove();
int res = it.next();
if (it.hasNext()) {
q.add(it);
}
return res;
}
public boolean hasNext() {
return !q.isEmpty();
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。