Flatten 2D Vector

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.