Monday, August 7, 2017

[Leetcode] Flatten 2D Vector, Solution

Implement an 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 be: [1,2,3,4,5,6].
Follow up:
As an added challenge, try to code it using only iterators in C++ or iterators in Java.

[Thoughts]
实现题,按层从左到右遍历。

[Code]
1:  class Vector2D {  
2:  public:  
3:    vector<vector<int>> data;  
4:    int x = 0;  
5:    int y = 0;  
6:    int total = 0;  
7:    int visited = 0;  
8:    Vector2D(vector<vector<int>>& vec2d) {  
9:      data = vec2d;  
10:      for(auto list : vec2d) {  
11:        total += list.size();  
12:      }  
13:    }  
14:    
15:    int next() {  
16:      while(data[x].size() == 0) {x++;}  
17:        
18:      int cur = data[x][y];  
19:      if(y+1 == data[x].size()) {  
20:        x = x+1;  
21:        y = 0;  
22:      } else {  
23:        y++;  
24:      }  
25:      visited ++;  
26:      return cur;  
27:    }  
28:    
29:    bool hasNext() {  
30:      if(visited < total) return true;  
31:        
32:      return false;  
33:    }  
34:  };  
35:    
36:  /**  
37:   * Your Vector2D object will be instantiated and called as such:  
38:   * Vector2D i(vec2d);  
39:   * while (i.hasNext()) cout << i.next();  
40:   */  






7 comments:

Serena Williams said...
This comment has been removed by the author.
James David said...

I have read this graphic blog just a note, the code has the less than, and greater than symbols (< >) mangled, likely expecting it to be used for HTML tags.
digitizing service

Briansmith5973 said...

It is wonderful all the things you can make on your own mind use. It is very informative for me and thanks for sharing.assignment writing service

James Anderson said...

I read your vector code is truly so amazing as a Ph.D. student I read so many complicated codes but this one is more than, I help in Cost Accounting Assignment Help to the student I help lots of student at very cheap price.

johnpatrick said...

To flatten a 2D vector, you can use the cross product. The cross product of two vectors, A and B, is given by the equation A × B = (a x b) + (c x d) where a, b, c, and d are the components of the vectors A and B. This information is gathered by professional book writing service.

Josephy said...

It’s going to be ending of mine day, but before ending I am reading this fantastic piece of writing to improve my knowledge. Great information, you have a wonderful blog and an excellent article. startup tips

Julia Robert said...

Nice post on the concerned subject of 2d vector. Your experience is great regarding vector tracing. Thank you very much...