[LeetCode]Flatten 2D Vector
public class Vector2D { int row; int r; int c; List<List<Integer>> num; public Vector2D(List<List<Integer>> vec2d) { this.num = vec2d; r = 0; c = 0; row = num.size(); } public int next() { while (r < row && c >= num.get(r).size()) { r ++; c = 0; } return num.get(r).get(c++); } public boolean hasNext() { while (r < row && c >= num.get(r).size()) { r ++; c = 0; } if (r >= row) { return false; } return c < num.get(r).size(); } }
Iterator解法
public class Vector2D { Iterator<List<Integer>> row_it; Iterator<Integer> col_it; List<List<Integer>> nums; public Vector2D(List<List<Integer>> vec2d) { this.nums = vec2d; row_it = nums.iterator(); if (row_it.hasNext()) { col_it = row_it.next().iterator(); } } public int next() { while(row_it.hasNext() && col_it != null && !col_it.hasNext()) { col_it = row_it.next().iterator(); } return col_it.next(); } public boolean hasNext() { while(row_it.hasNext() && col_it != null && !col_it.hasNext()) { col_it = row_it.next().iterator(); } if (col_it == null || !col_it.hasNext()) { return false; } return true; } }