Implement an iterator to flatten a 2d vector.
For example,
Given 2d vector =
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.
Solution:
Reference: http://buttercola.blogspot.com/2015/08/leetcode-flatten-2d-vector.html
Inner iterator must be initilized as Collections.emptyIterator() because the method hasNext() first checks if the innerIterator.hasNext(), so the inner iterator itself must be an iterator at first.
public class Vector2D { ListFollow Up: using only iterators in C++ or iterators in Javaflat; int index; public Vector2D(List > vec2d) { index = 0; flat = new ArrayList
(); for (int i = 0; i < vec2d.size(); i++) { for (int j = 0; j < vec2d.get(i).size(); j++) { flat.add(vec2d.get(i).get(j)); } } } public int next() { int val = flat.get(index); index++; return val; } public boolean hasNext() { return index < flat.size(); } } /** * Your Vector2D object will be instantiated and called as such: * Vector2D i = new Vector2D(vec2d); * while (i.hasNext()) v[f()] = i.next(); */
Reference: http://buttercola.blogspot.com/2015/08/leetcode-flatten-2d-vector.html
Inner iterator must be initilized as Collections.emptyIterator() because the method hasNext() first checks if the innerIterator.hasNext(), so the inner iterator itself must be an iterator at first.
public class Vector2D { Iterator> outer; Iterator
inner; public Vector2D(List > vec2d) { outer = vec2d.iterator(); inner = Collections.emptyIterator(); // if outer == null, inner = outer.iterator() will throw exception } public int next() { return inner.next(); } public boolean hasNext() { if (inner.hasNext()) { return true; } if (!outer.hasNext()) { return false; } inner = outer.next().iterator(); while (!inner.hasNext() && outer.hasNext()) { inner = outer.next().iterator(); } return inner.hasNext(); } } /** * Your Vector2D object will be instantiated and called as such: * Vector2D i = new Vector2D(vec2d); * while (i.hasNext()) v[f()] = i.next(); */
No comments:
Post a Comment