LeetCode: Zig Zag Iterator II

/**
Zigzag Iterator II
Follow up Zigzag Iterator: 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".
Example Given k = 3 1d vectors:
[1,2,3]
[4,5,6,7]
[8,9]
Return [1,4,8,2,5,9,3,6,7].
*/
import java.util.*;

public class ZigZagIteratorII{

List<Iterator<Integer>> its;
int cur = 0;

public ZigZagIteratorII(List<List<Integer>> lists){
its = new ArrayList<Iterator<Integer>>();
for(List<Integer> list:lists){
its.add(list.iterator());
}
}

public boolean hasNext(){
return its.size()>0;
}

public int next(){
if(!hasNext()) return -1;
int val = its.get(cur).next();
if(its.get(cur).hasNext()){
cur= (cur +1)%its.size();
}else{
its.remove(cur);
if(its.size()>0){
cur = cur%its.size();
}
}
return val;
}
}

No comments:

Post a Comment