稀疏数组
用(n+1)*3列的新数组压缩原始数组,n 代表非零元素的个数。新数组第一行存储原始数组总的行数、列数和非零元素个数,剩余行表示非零元素的位置和数值
转化代码
public static int[][] toSparse(int[][] arr) {
int count = 0;
//统计非0元素个数
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] != 0) {
count++;
}
}
}
int[][] result = new int[count + 1][3];
//原始数组行数
result[0][0] = arr.length;
//原始数组列数
result[0][1] = arr[0].length;
//非0元素个数
result[0][2] = count;
//非0元素在新数组中行位置
int index = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] != 0) {
index++;
//行下标
result[index][0] = i;
//列下标
result[index][1] = j;
//值
result[index][2] = arr[i][j];
}
}
}
return result;
}