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

LeetCode-Flatten 2D Vector

时间:2016-08-23 14:35:20      阅读:136      评论: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].

Follow up:
As an added challenge, try to code it using only iterators in C++ or iterators in Java.

Solution:

 1 public class Vector2D implements Iterator<Integer> {
 2     List<List<Integer>> vecs;
 3     int curIndex;
 4     Iterator<Integer> iter;
 5 
 6     public Vector2D(List<List<Integer>> vec2d) {
 7         vecs = vec2d;
 8         curIndex = 0;
 9         if (curIndex >= vecs.size()) return;
10         iter = vecs.get(curIndex).iterator();
11         moveToNext();
12     }
13 
14     private void moveToNext() {
15         while (!iter.hasNext()) {
16             curIndex++;
17             if (curIndex >= vecs.size())
18                 break;
19             iter = vecs.get(curIndex).iterator();
20         }
21     }
22 
23     @Override
24     public Integer next() {
25         if (curIndex >= vecs.size())
26             return null;
27 
28         Integer res = iter.next();
29         moveToNext();
30         
31         return res;
32     }
33 
34     @Override
35     public boolean hasNext() {
36         return curIndex < vecs.size();
37     }
38 }

 

LeetCode-Flatten 2D Vector

标签:

原文地址:http://www.cnblogs.com/lishiblog/p/5799051.html

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