Recognition: When most elements in an array are 0 or the same data, a sparse array can be used to store its effective information.
Purpose: To reduce waste of storage space, compress data size, and save only useful information
Storage method:
Stored in a two-dimensional array, in a sparse array
6 Represented by a sparse array: arr [0] [0];
7 Represented by a sparse array: arr [0] [1];
8 Represented by a sparse array: arr [0] [2];
5 Represented by a sparse array: arr [8] [0];
2 Represented by a sparse array: arr [8] [1];
28 Represented by a sparse array: arr [8] [2];
Schematic representation of multi-dimensional array:
Schematic diagram of converting a two-dimensional matrix into a sparse array:
package array;
public class ArrayDemo06 {
public static void main(String[] args) {
int[][] arr1 = new int[5][5];
arr1[1][2] = 1;
arr1[2][3] = 2;
System.out.println("原始二维数组:");
for (int[] ints : arr1) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}
/*
变为稀疏数组
*///获取有用数据的个数 int sum = 0; for (int i = 0; i < arr1.length; i++) { for (int j = 0; j < arr1[i].length; j++) { if(arr1[i][j] != 0){ sum++; } } } //获取数组总共有几行、几列(arr1.length,arr1[0].length) //构建稀疏数组 int[][] arr2 = new int[sum+1][3]; arr2[0][0] = arr1.length; arr2[0][1] = arr1[0].length; arr2[0][2] = sum; //获取有用数据的行、列、值,赋值稀疏矩阵 int num=0; for (int i = 0; i < arr1.length; i++) { for (int j = 0; j < arr1.length; j++) { if(arr1[i][j] != 0){ num++; arr2[num][0] = i; arr2[num][1] = j; arr2[num][2] =arr1[i][j]; } } } //稀疏数组的输出 System.out.println("稀疏数组的输出:"); for (int[] ints : arr2) { for (int anInt : ints) { System.out.print(anInt+"\t"); } System.out.println(); } /* 稀疏数组还原为二维数组 */ //二维数组赋值 int[][] arr3 = new int[arr2[0][0]][arr2[0][1]]; for (int i = 1; i < arr2.length; i++) { arr3[arr2[i][0]][arr2[i][1]] = arr2[i][2]; } //二维数组输出 System.out.println("还原数组输出:"); for (int[] ints : arr3) { for (int anInt : ints) { System.out.print(anInt+"\t"); } System.out.println(); } }
}
原始二维数组: 0 0 0 0 0 0 0 1 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 稀疏数组的输出: 5 5 2 1 2 1 2 3 2 还原数组输出: 0 0 0 0 0 0 0 1 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0