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?Show More Hint
- Two variables is all you need. Try with
x
andy
.Show More Hint - Beware of empty rows. It could be the first few rows.Show More Hint
- To write correct code, think about the invariant to maintain. What is it?Show More Hint
- 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?Show More Hint - Not sure? Think about how you would implement
hasNext()
. Which is more complex?Show More Hint - Common logic in two different places should be refactored into a common method.
Follow up:
As an added challenge, try to code it using only iterators in C++ or iterators in Java.
public class Vector2D {
int i = 0;
int j = -1;
List<List<Integer>> data;
public Vector2D(List<List<Integer>> vec2d) {
data = vec2d;
int i = 0;
int j = 0;
}
public int next() {
j++;
while (i < data.size() && j >= data.get(i).size()) {
j = 0;
i++;
}
return data.get(i).get(j);
}
public boolean hasNext() {
int tmpJ = j;
int tmpI = i;
tmpJ++;
while (tmpI < data.size() && tmpJ >= data.get(tmpI).size()) {
tmpJ = 0;
tmpI++;
}
return tmpI != data.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 {
Iterator<List<Integer>> iterator1;
Iterator<Integer> iterator2;
public Vector2D(List<List<Integer>> vec2d) {
iterator1 = vec2d.iterator();
iterator2 = null;
}
public int next() {
while (iterator2 == null || !iterator2.hasNext()) {
iterator2 = iterator1.next().iterator();
}
return iterator2.next();
}
public boolean hasNext() {
while (iterator2 == null || !iterator2.hasNext()) {
if (iterator1.hasNext()) {
iterator2 = iterator1.next().iterator();
} else {
break;
}
}
return iterator2 != null && iterator2.hasNext();
}
}
/**
* Your Vector2D object will be instantiated and called as such:
* Vector2D i = new Vector2D(vec2d);
* while (i.hasNext()) v[f()] = i.next();
*/
没有评论:
发表评论