251. Flatten 2D Vector

Source: Internet
Author: User

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:

  1. How many variables does you need to keep track?
  2. Variables are all need. Try with x and y .
  3. Beware of empty rows. It could be the first few rows.
  4. To write correct code, think on the invariant to maintain. What is it?
  5. 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?
  6. Not sure? Think about what you would implement hasNext() . Which is more complex?
  7. Common logic in the different places should is refactored into a Common method.

 Public classvector2d { Publicilist<ilist<int>> v {Get;Set;} Private intVerticalcount {Get;Set;} Private intIndex {Get;Set;}  PublicVector2d (ilist<ilist<int>>vec2d) {v=vec2d; Verticalcount=0; Index=0; }     Public BOOLHasnext () {if(Verticalcount >= v.count ())return false; if(Verticalcount = = V.count ()-1&& index >= V[verticalcount]. Count ())return false; if(Index >=V[verticalcount]. Count ()) {Verticalcount++;  while(Verticalcount < V.count () && V[verticalcount]. Count () = =0) {Verticalcount++; }            if(Verticalcount = = V.count ())return false; Else{Index=0; return true; }                   }        return true; }     Public intNext () {returnv[verticalcount][index++]; }}/** * Your vector2d'll be a called like this : * vector2d i = new vector2d (vec2d), * while (I.hasnext ()) v[f ()] = I.next ( ); */

251. 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.