Google
281 Zigzag Iterator

1. Question

Given two 1d vectors, implement an iterator to return their elements alternately.
For example, given two 1d vectors:
1
v1 = [1, 2]
2
v2 = [3, 4, 5, 6]
Copied!
By callingnextrepeatedly untilhasNextreturnsfalse, the order of elements returned bynextshould be:[1, 3, 2, 4, 5, 6].
Follow up: What if you are givenk1d 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
[1,2,3]
2
[4,5,6,7]
3
[8,9]
Copied!
It should return
[1,4,8,2,5,9,3,6,7].

2. Implementation

思路: 用LinkedList或者Queue存每个输入list的iterator,这样就可以解决follow-up里的k 个vector的问题
1
public class ZigzagIterator {
2
LinkedList<Iterator> list;
3
4
public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
5
list = new LinkedList<Iterator>();
6
if (!v1.isEmpty()) {
7
list.add(v1.iterator());
8
}
9
10
if (!v2.isEmpty()) {
11
list.add(v2.iterator());
12
}
13
}
14
15
public int next() {
16
Iterator curIT = list.remove();
17
int res = (Integer)curIT.next();
18
if (curIT.hasNext()) {
19
list.add(curIT);
20
}
21
return res;
22
}
23
24
public boolean hasNext() {
25
return !list.isEmpty();
26
}
27
}
28
29
/**
30
* Your ZigzagIterator object will be instantiated and called as such:
31
* ZigzagIterator i = new ZigzagIterator(v1, v2);
32
* while (i.hasNext()) v[f()] = i.next();
33
*/
Copied!

3. Time & Space Complexity

时间复杂度: next(): O(1), hasNext(): O(1), 空间复杂度O(k), k是输入list的个数