首页 > 其他 > 详细

Leetcode: Flatten 2D Vector

时间:2015-12-22 08:57:21      阅读:114      评论:0      收藏:0      [点我收藏+]
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].

I think the hint provided by Leetcode is good:

Hint:

  1. How many variables do you need to keep track?
  2. Two variables is all you need. Try with x and y
  3. Beware of empty rows. It could be the first few rows.
  4. To write correct code, think about the invariant to maintain. What is it?
  5. The invariant is x and y must always point to a valid point in the 2d vector. Should you maintain your invariant ahead of time or right when you need it?
  6. Not sure? Think about how you would implement hasNext(). Which is more complex?
  7. Common logic in two different places should be refactored into a common method.

So we maintain a set of (x, y), where they point to a valid none empty point in this 2d vector, and this point is also the next element that is going to return. When initializing, set (x, y) to be the first position of a none empty valid point. Every time after calling Next() function, set it to be the next valid position. y++ or y=0 when switch rows. Continue the process until x reaches vec.size()

 1 public class Vector2D {
 2     List<List<Integer>> vec;
 3     int len;
 4     int x;
 5     int y;
 6 
 7     public Vector2D(List<List<Integer>> vec2d) {
 8         this.vec = vec2d;
 9         this.len = vec.size();
10         int i = 0;
11         while (i<len && vec.get(i).size() == 0) {
12             i++;
13         }
14         this.x = i;
15         this.y = 0;
16     }
17 
18     public int next() {
19         int result = Integer.MAX_VALUE;
20         if (hasNext()) {
21             result = vec.get(x).get(y);
22             if (y < vec.get(x).size()-1) y++;
23             else {
24                 x++;
25                 while (x<vec.size() && vec.get(x).size()==0) {
26                     x++;
27                 }
28                 y = 0;
29             }
30         }
31         return result;
32     }
33 
34     public boolean hasNext() {
35         return (x<len)? true : false;
36     }
37 }
38 
39 /**
40  * Your Vector2D object will be instantiated and called as such:
41  * Vector2D i = new Vector2D(vec2d);
42  * while (i.hasNext()) v[f()] = i.next();
43  */

 

Leetcode: Flatten 2D Vector

原文:http://www.cnblogs.com/EdwardLiu/p/5065501.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!