题目地址:
https://leetcode.com/problems/flatten-2d-vector/
给定一个二维数组,要求设计一个迭代器,可以让用户按照逐行从上到下,每行从左到右的顺序遍历。题目保证每次调用next的时候都是合法的。
思路是用两个变量记录当前在v的哪一行哪一列,并另开一个函数gotoNext,专门用来返回下一个有效的位置(有效的意思是,到达需要遍历到的下一个数字),如果不存在有效位置了,就返回null。在调用hasNext的时候,直接调用gotoNext看是否返回null;在调用next的时候,先调用gotoNext返回的坐标,然后返回数值。代码如下:
class Vector2D {
private int[][] v;
private int row, col;
public Vector2D(int[][] v) {
this.v = v;
// 把坐标初始化为(0, 0)的上一个位置,定义为(0, -1)
row = 0;
col = -1;
}
public int next() {
int[] pos = gotoNext(row, col);
row = pos[0];
col = pos[1];
return v[row][col];
}
public boolean hasNext() {
return gotoNext(row, col) != null;
}
// 返回从row,col开始走的下一个要访问的坐标;若不存在则返回null
private int[] gotoNext(int row, int col) {
// 这句话专门用来特判整个二维数组都空的情况
if (v.length == 0) {
return null;
}
// 向右走一步
col++;
// 如果走出界了,就重置为0,行向下走一步
if (col == v[row].length) {
col = 0;
row++;
}
// 走到外面了,说明遍历完了,返回null
if (row == v.length) {
return null;
}
// 略过空行
while (row < v.length && v[row].length == 0) {
row++;
}
// 如果都是空行,走到末尾了,也返回null;否则返回坐标
return row == v.length ? null : new int[]{row, col};
}
}
时间复杂度 O ( n ) O(n) O(n)( n n n是二维数组的规模),空间 O ( 1 ) O(1) O(1)。