原题网址:https://leetcode.com/problems/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]
.
Hint:
- How many variables do you need to keep track?
- Two variables is all you need. Try with
x
andy
. - Beware of empty rows. It could be the first few rows.
- To write correct code, think about the invariant to maintain. What is it?
- The invariant is
x
andy
must always point to a valid point in the 2d vector. Should you maintain your invariant ahead of time or right when you need it? - Not sure? Think about how you would implement
hasNext()
. Which is more complex? - Common logic in two different places should be refactored into a common method.
思路:用两个变量保存二维向量的当前位置。
public class Vector2D implements Iterator<Integer> {
private int row , col;
private List<List<Integer>> vec2d;
public Vector2D(List<List<Integer>> vec2d) {
this.vec2d = vec2d;
while (row <vec2d.size() && col >= vec2d.get(row).size()) {
col = 0;
row ++;
}
}
@Override
public Integer next() {
Integer value = vec2d.get(row).get(col);
col ++;
while (row <vec2d.size() && col >= vec2d.get(row).size()) {
col = 0;
row ++;
}
return value;
}
@Override
public boolean hasNext() {
return row < vec2d.size() && col < vec2d.get(row).size();
}
}
/**
* Your Vector2D object will be instantiated and called as such:
* Vector2D i = new Vector2D(vec2d);
* while (i.hasNext()) v[f()] = i.next();
*/
类似方法:
public class Vector2D implements Iterator<Integer> {
private List<List<Integer>> vec2d;
private int i, j;
public Vector2D(List<List<Integer>> vec2d) {
this.vec2d = vec2d;
}
@Override
public Integer next() {
hasNext();
return this.vec2d.get(i).get(j++);
}
@Override
public boolean hasNext() {
for(; i<vec2d.size(); i++) {
if (j<vec2d.get(i).size()) return true;
j=0;
}
return false;
}
}
/**
* Your Vector2D object will be instantiated and called as such:
* Vector2D i = new Vector2D(vec2d);
* while (i.hasNext()) v[f()] = i.next();
*/