Design and implement an iterator to flatten a 2d vector. It should support the following operations: next
and hasNext
.
Example:
Vector2D iterator = new Vector2D([[1,2],[3],[4]]); iterator.next(); // return 1 iterator.next(); // return 2 iterator.next(); // return 3 iterator.hasNext(); // return true iterator.hasNext(); // return true iterator.next(); // return 4 iterator.hasNext(); // return false
Notes:
- Please remember to RESET your class variables declared in Vector2D, as static/class variables are persisted across multiple test cases. Please see here for more details.
- You may assume that
next()
call will always be valid, that is, there will be at least a next element in the 2d vector whennext()
is called.
展开二维向量。
这也是一道考察iterator的题目,只不过是把iterate的对象变成了一个二维数组。比较偷懒的办法就是先把所有元素放入一个队列,然后遍历队列即可。
Java实现
1 class Vector2D { 2 private Queue<Integer> queue = new LinkedList<>(); 3 4 public Vector2D(int[][] v) { 5 for (int i = 0; i < v.length; i++) { 6 for (int j = 0; j < v[i].length; j++) { 7 queue.offer(v[i][j]); 8 } 9 } 10 } 11 12 public int next() { 13 return queue.poll(); 14 } 15 16 public boolean hasNext() { 17 return !queue.isEmpty(); 18 } 19 } 20 21 /** 22 * Your Vector2D object will be instantiated and called as such: 23 * Vector2D obj = new Vector2D(v); 24 * int param_1 = obj.next(); 25 * boolean param_2 = obj.hasNext(); 26 */
不使用队列也能做,无非考察的是你对遍历二维矩阵的坐标的敏感程度。注意这道题给的二维向量,每一行的元素个数并不一样,所以不能用类似遍历二维矩阵那样的方式去遍历。
Java实现
1 class Vector2D { 2 int[][] v; 3 int i = 0; 4 int j = 0; 5 6 public Vector2D(int[][] v) { 7 this.v = v; 8 } 9 10 public int next() { 11 if (hasNext()) { 12 return v[i][j++]; 13 } else { 14 return -1; 15 } 16 } 17 18 public boolean hasNext() { 19 while (i < v.length && j == v[i].length) { 20 i++; 21 j = 0; 22 } 23 return i < v.length; 24 } 25 } 26 27 /** 28 * Your Vector2D object will be instantiated and called as such: 29 * Vector2D obj = new Vector2D(v); 30 * int param_1 = obj.next(); 31 * boolean param_2 = obj.hasNext(); 32 */