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?
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].
Tips:
对iterator的定义和写法不是很清晰,算法倒是比较简洁明了。借鉴了discuss做出来,但是并不是很难。
两个数组的合并,穿插进行。
Follow up 要新建arraylist iterator。
//解法1:
public class ZigzagIterator {
Iterator<Integer> it1;
Iterator<Integer> it2;
int turns;
public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
this.it1 = v1.iterator();
this.it2 = v2.iterator();
turns = 0;
}
public int next() {
// 如果没有下一个则返回0
if(!hasNext()){
return 0;
}
turns++;
// 如果是第奇数个,且第一个列表也有下一个元素时,返回第一个列表的下一个
// 如果第二个列表已经没有,返回第一个列表的下一个
if((turns % 2 == 1 && it1.hasNext()) || (!it2.hasNext())){
return it1.next();
// 如果是第偶数个,且第二个列表也有下一个元素时,返回第二个列表的下一个
// 如果第一个列表已经没有,返回第二个列表的下一个
} else if((turns % 2 == 0 && it2.hasNext()) || (!it1.hasNext())){
return it2.next();
}
return 0;
}
public boolean hasNext() {
return it1.hasNext() || it2.hasNext();
}
}
//解法2:
public class ZigzagIterator {
int index;
boolean count;
List<Integer> v1;
List<Integer> v2;
public ZigzagIterator (List<Integer> v1, List<Integer> v2) {
this.index = 0;
this.count = true;
this.v1 = v1;
this.v2 = v2;
}
public int next() {
int result;
if (count && index < v1.size()) {
result = v1.get(index);
if (index < v2.size()) {
count = !count;
} else {
index++;
}
} else {
result = v2.get(index++);
if (index < v1.size()) {
count = !count;
}
}
return result;
}
public boolean hasNext() {
return index < v1.size() || index < v2.size();
}
}
/**
- Your ZigzagIterator object will be instantiated and called as such:
- ZigzagIterator i = new ZigzagIterator(v1, v2);
- while (i.hasNext()) v[f()] = i.next(); */
## follow up:
public class ZigzagIterator implements Iterator<Integer> {
List<Iterator<Integer>> itlist;
int turns;
public ZigzagIterator(List<Iterator<Integer>> list) {
this.itlist = new LinkedList<Iterator<Integer>>();
// 将非空迭代器加入列表
for(Iterator<Integer> it : list){
if(it.hasNext()){
itlist.add(it);
}
}
turns = 0;
}
public Integer next() {
if(!hasNext()){
return 0;
}
Integer res = 0;
// 算出本次使用的迭代器的下标
int pos = turns % itlist.size();
Iterator<Integer> curr = itlist.get(pos);
res = curr.next();
// 如果这个迭代器用完,就将其从列表中移出
if(!curr.hasNext()){
itlist.remove(turns % itlist.size());
// turns变量更新为上一个下标
turns = pos - 1;
}
turns++;
return res;
}
public boolean hasNext() {
return itlist.size() > 0;
}
}