Zigzag Iterator 540
Question
Given two 1d vectors, implement an iterator to return their elements alternately.
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].
Solution
这道题可以直接调用list的iterator来实现,只要用一个计数来确定应该用哪个iteraor即可。当然也可以自己用两个index来实现,但是iterator在内存中占用空间更小,并且更方便操作。
代码如下:
public class ZigzagIterator {
/**
* @param v1 v2 two 1d vectors
*/
//用iterator更省空间
Iterator<Integer> it1;
Iterator<Integer> it2;
int count;
public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
// initialize your data structure here.
it1 = v1.iterator();
it2 = v2.iterator();
count = 0;
}
public int next() {
// Write your code here
count++;
if((count % 2 == 1 && it1.hasNext()) || !it2.hasNext()){
return it1.next();
}else if((count % 2 == 0 && it2.hasNext()) || !it1.hasNext()){
return it2.next();
}
return -1;
}
public boolean hasNext() {
// Write your code here
return it1.hasNext() || it2.hasNext();
}
}
/**
* Your ZigzagIterator object will be instantiated and called as such:
* ZigzagIterator solution = new ZigzagIterator(v1, v2);
* while (solution.hasNext()) result.add(solution.next());
* Output result
*/