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?
Clarification for the follow up question - Update (2015-09-18):
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]
.
k = 2
这道题可以直接调用list的iterator来实现,只要用一个计数来确定应该用哪个iteraor即可。当然也可以自己用两个index来实现,但是iterator在内存中占用空间更小,并且更方便操作
public class ZigzagIterator {
Iterator<Integer> it1;
Iterator<Integer> it2;
int count;
public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
it1 = v1.iterator();
it2 = v2.iterator();
count = 0;
}
public int next() {
count++;
if ((count % 2 == 1 && it1.hasNext()) || !it2.hasNext()) {
return it1.next();
} else if ((count % 2 == 0 && it2.hasNext()) || !it1.hasNext()) {
return it2.next();
} else {
return -1;
}
}
public boolean hasNext() {
return it1.hasNext() || it2.hasNext();
}
}
K > 2
和k = 2类似,只是用一个list来存k个iterator(如果iterator中没有元素则不用加入)。用一个count%list_size来确定应该用哪个iterator。若其中一个iterator里面的数已经被取完(即该iterator的hasNext()为false),则将其从list中移除,并将count设置为count%new list_size(如果new list_size != 0)
public class ZigzagIterator2 {
List<Iterator<Integer>> vec;
int count;
public ZigzagIterator2(List<List<Integer>> vecs) {
vec = new ArrayList<>();
for (List<Integer> list : vecs) {
if (list.size() > 0) {
vec.add(list.iterator());
}
}
count = 0;
}
public int next() {
int res = vec.get(count).next();
if (vec.get(count).hasNext()) {
count = (count + 1) % vec.size();
} else {
vec.remove(count);
if (vec.size() > 0) {
count %= vec.size();
}
}
return res;
}
public boolean hasNext() {
return vec.size() > 0;
}
}