Implement a 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 is: [1,2,3,4,5,6]
.
Analysis: 1190000003791233
An array is used to represent the iterator for each list, and then a variable is recorded to indicate that the first iterator is currently used.
1 Public classvector2d {2 3List<iterator<integer>>its ;4 intCurr =0;5 6 PublicVector2d (list<list<integer>>vec2d) {7 This. its =NewArraylist<iterator<integer>>();8 for(list<integer>l:vec2d) {9 //add only non-null iterators to the arrayTen if(L.size () >0) { One This. Its.add (L.iterator ()); A } - } - } the - Public intNext () { -Integer res = its.Get(Curr). Next (); - //if the iterator is finished, switch to the next + if(!its.Get(Curr). Hasnext ()) { -curr++; + } A returnRes; at } - - PublicBoolean hasnext () { - returnCurr < Its.size () && its.Get(Curr). Hasnext (); - } -}
Flatten 2D Vector