码迷,mamicode.com
首页 > 其他好文 > 详细

Flatten 2D Vector

时间:2016-08-05 06:39:20      阅读:115      评论: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].

分析:https://segmentfault.com/a/1190000003791233

用一个数组表示每个List的迭代器,然后再记录一个变量,用来表示当前用到了第几个迭代器。

 1 public class Vector2D {
 2 
 3     List<Iterator<Integer>> its;
 4     int curr = 0;
 5 
 6     public Vector2D(List<List<Integer>> vec2d) {
 7         this.its = new ArrayList<Iterator<Integer>>();
 8         for (List<Integer> l : vec2d) {
 9             // 只将非空的迭代器加入数组
10             if (l.size() > 0) {
11                 this.its.add(l.iterator());
12             }
13         }
14     }
15 
16     public int next() {
17         Integer res = its.get(curr).next();
18         // 如果该迭代器用完了,换到下一个
19         if (!its.get(curr).hasNext()) {
20             curr++;
21         }
22         return res;
23     }
24 
25     public boolean hasNext() {
26         return curr < its.size() && its.get(curr).hasNext();
27     }
28 }

 

Flatten 2D Vector

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5739787.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!