• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 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].

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  */

 

posted @ 2015-12-22 08:13  neverlandly  阅读(281)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3