Implement a iterator to flatten a 2d vector.
For example,
Given 2d vector =
[ [up], [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 does you need to keep track?
- Variables are all need. Try with
x
and y
.
- Beware of empty rows. It could be the first few rows.
- To write correct code, think on the invariant to maintain. What is it?
- The invariant is
x
and y
must all-point-a valid point in the 2d vector. Should maintain your invariant ahead of time or right when do you need it?
- Not sure? Think about what you would implement
hasNext()
. Which is more complex?
- Common logic in the different places should is refactored into a Common method.
Follow up:
As an added challenge, try to code it using only iterators in C + + or iterators in Java.
Solution One: Without iterator
Public classVector2dImplementsIterator<integer> { intindexlist; intIndexele; List<List<Integer>>VEC; PublicVector2d (list<list<integer>>vec2d) {Indexlist= 0; Indexele= 0; VEC=vec2d; } @Override PublicInteger Next () {Hasnext (); returnVec.get (indexlist). Get (indexele++); } @Override Public BooleanHasnext () { while(indexlist<vec.size ()) { if(Indexele<vec.get (indexlist). Size ())return true; Else{indexlist++; Indexele=0; } } return false; } }/*** Your vector2d object would be instantiated and called as such: * vector2d i = new vector2d (vec2d), * while (I.hasnex T ()) v[f ()] = I.next (); */
Solution two: With iterator
Public classVector2dImplementsIterator<integer> { PrivateIterator<list<integer>>i; PrivateIterator<integer>J; PublicVector2d (list<list<integer>>vec2d) {i=Vec2d.iterator (); } PublicInteger Next () {Hasnext (); returnJ.next (); } Public BooleanHasnext () { while(J = =NULL|| !j.hasnext ()) &&I.hasnext ()) J=I.next (). iterator (); returnJ! =NULL&&J.hasnext (); }}/*** Your vector2d object would be instantiated and called as such: * vector2d i = new vector2d (vec2d), * while (I.hasnex T ()) v[f ()] = I.next (); */
Reference
Https://discuss.leetcode.com/topic/20697/7-9-lines-added-java-and-c-o-1-space/2
Flatten 2D Vector