Flatten 2D Vector

Implement an iterator to flatten a 2d vector.

For example, Given 2d vector =

[
[1,2],
[3],
[4,5,6]
]

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,2,3,4,5,6].

分析:https://segmentfault.com/a/1190000003791233

用一个数组表示每个List的迭代器,然后再记录一个变量,用来表示当前用到了第几个迭代器。

 public class Vector2D {

     List<Iterator<Integer>> its;
int curr = ; public Vector2D(List<List<Integer>> vec2d) {
this.its = new ArrayList<Iterator<Integer>>();
for (List<Integer> l : vec2d) {
// 只将非空的迭代器加入数组
if (l.size() > ) {
this.its.add(l.iterator());
}
}
} public int next() {
Integer res = its.get(curr).next();
// 如果该迭代器用完了,换到下一个
if (!its.get(curr).hasNext()) {
curr++;
}
return res;
} public boolean hasNext() {
return curr < its.size() && its.get(curr).hasNext();
}
}
上一篇:php中的魔术方法


下一篇:OS X Framework Library not loaded: 'Image not found'的解决办法