2015年11月4日星期三

Leetcode 251 Flatten 2D Vector

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].
Solution 1: simple design problem.
 public class Vector2D {  
   List<List<Integer>> vec2d;  
   int i;  
   int j;  
   public Vector2D(List<List<Integer>> vec2d) {  
     this.vec2d=vec2d;  
     i=0;  
     j=0;  
     while (i<vec2d.size() && j>=vec2d.get(i).size()) {  
       i++;  
       j=0;  
     }  
   }  
   public int next() {  
     int res=vec2d.get(i).get(j);  
     j++;  
     while (i<vec2d.size() && j>=vec2d.get(i).size()) {  
       i++;  
       j=0;  
     }  
     return res;  
   }  
   public boolean hasNext() {  
     return i<vec2d.size();  
   }  
 }  

没有评论:

发表评论