稀疏数组
原理:即在一个二维数组内,如果有很多空间都存放着默认值或者同一个值,那么其他值可以视为有效数字,可以把有效数字单独拿出来新建一个二维数组,即原二维数组的稀疏数组。
样例二维数组
32 | |||||||||
---|---|---|---|---|---|---|---|---|---|
2 | |||||||||
9 | |||||||||
11 | |||||||||
18 |
目标稀疏数组
行 列 值
10 | 10 | 5 |
---|---|---|
0 | 5 | 32 |
1 | 1 | 2 |
3 | 3 | 9 |
7 | 2 | 11 |
9 | 4 | 18 |
代码展示
public class Demo01 {
public static void main(String[] args) {
// 1.创建一个二维数组并给其中不为默认值的空间赋值(有效数字)
int[][] array1 = new int[10][10];
array1[0][5] = 32;
array1[1][1] = 2;
array1[3][3] = 9;
array1[7][2] = 11;
array1[9][4] = 18;
// 2.for-each(增强型for循环)来遍历输出一次目标原二维数组
for (int[] ints : array1) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}
System.out.println("====================================================================");
// 3.查找原数组内的有效数字个数作为稀疏数组的第一行
int count = 0; //count 即为有效数字的个数
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array1[i].length; j++) {
if (array1[i][j]!=0){
count++;
}
}
}
System.out.println(count);
System.out.println("====================================================================");
// 4.创建新数组array2稀疏数组来存放有效数字
int[][] array2 = new int[count+1][3];
array2[0][0] = 10;
array2[0][1] = 10;
array2[0][2] = count;
// 第一行创建完成
int count2 = 0; //count2++ 相当于遍历到一个有效数字之后,稀疏数组的行加一
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array1[i].length; j++) {
if (array1[i][j]!= 0){
count2++;
array2[count2][0] = i;
array2[count2][1] = j;
array2[count2][2] = array1[i][j];
}
}
}
// 5.遍历打印新稀疏数组看结果是否正确
for (int[] ints : array2) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}
System.out.println("===================================================================");
// 6.把稀疏数组array2还原为原始数组,并存为新数组array3
int[][] array3 = new int[array2[0][0]][array2[0][1]]; //直接用稀疏数组第一行的行列信息作为还原数组的行列值
for (int i = 1; i < array2.length; i++) { //i从1开始是因为稀疏数组的有效数字行从第2行开始
for (int j = 0; j < array2[i].length; j++) {
array3[array2[i][0]][array2[i][1]] = array2[i][2]; //用稀疏数组内的信息表示还原数组的各数字位置
}
}
// 7.再次打印还原数组
for (int[] ints : array3) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}
}
}