My code:
public class Vector2D {
private int lineNum = 0;
private int index = 0;
private List<List<Integer>> l;
int k = 0;
public Vector2D(List<List<Integer>> vec2d) {
l = vec2d;
k = vec2d.size();
}
public int next() {
int ret = l.get(lineNum).get(index);
index++;
if (index >= l.get(lineNum).size()) {
index = 0;
lineNum++;
}
return ret;
}
public boolean hasNext() {
while (lineNum < k) {
if (l.get(lineNum).size() != 0)
return true;
lineNum++;
}
return false;
}
}
/**
* Your Vector2D object will be instantiated and called as such:
* Vector2D i = new Vector2D(vec2d);
* while (i.hasNext()) v[f()] = i.next();
*/
这道题目不是很难。但是一个corner case 一直卡住,也没能想出为什么。直到用了eclipse debug之后才知道。
如果 list 里面有空的list,但是他又算一行,所以 hasNext() 无法检测出来。
这个时候,index = 0,从他里面取出元素的话,会发生溢出。
然后我就想着从next里面规避这种情况。
**
但是,这个想法,是大错特错的!!
规避溢出的唯一思路,就是从 hasNext() 入手。next() 永远不需要考虑是否会溢出。直接取。
hasNext() 负责判断溢出!
**
Anyway, Good luck, RIchardo!
My code:
public class Vector2D implements Iterator<Integer> {
List<Iterator<Integer>> list = new ArrayList<Iterator<Integer>>();
int counter = 0;
int total = 0;
public Vector2D(List<List<Integer>> vec2d) {
for (List<Integer> temp : vec2d) {
list.add(temp.iterator());
}
total = vec2d.size();
}
@Override
public Integer next() {
return list.get(counter).next();
}
@Override
public boolean hasNext() {
while (counter < total) {
if (list.get(counter).hasNext()) {
return true;
}
else {
counter++;
}
}
return false;
}
}
/**
* Your Vector2D object will be instantiated and called as such:
* Vector2D i = new Vector2D(vec2d);
* while (i.hasNext()) v[f()] = i.next();
*/
这些还是可以用, List<Iterator> 的思路来做。
不难。
Anyway, Good luck, Richardo! -- 09/14/2016