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 }
时间: 2024-11-05 11:41:57