Basic introduction
Most of the elements in an array are 0 when , Or for the same value , You can use a sparse array to hold the array . This can save space , Increase of efficiency .
processing method
- Record the number of rows and columns in a two-dimensional array , How many different values
- Record rows and columns and values of elements with different values in a small array , To reduce the size of the program .
Realize the idea
Two dimensional array To Sparse array :
- Traverse the original two-dimensional array , Get the blame 0 Number count
- Building sparse arrays
sparseArr[count+][3]
- Two dimensional array is not 0 Elements are stored in sparse arrays
Sparse array To a two-dimensional array
- Read the first line of the sparse array , Build the original two-dimensional array
- Traversing the remaining elements of a sparse array , Fill in a two-dimensional array
public class SparseArray {
public static void main(String[] args) {
// Create an original two-dimensional array [11][11]
//0: No chess pieces , 1: The spots 2: Blueberry
int[][] arr = new int[11][11];
arr[1][2] = 1;
arr[2][3] = 2;
for (int[] row : arr) {
for (int item : row) {
System.out.printf("%d\t", item);
}
System.out.println();
}
// Traversing a two-dimensional array , Get the blame 0 Number of data
int count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] != 0) {
count++;
}
}
}
// Create the corresponding sparse array
int[][] sparseArr = new int[count + 1][3];
// Assign values to sparse arrays
sparseArr[0][0] = arr.length;
sparseArr[0][1] = arr[0].length;
sparseArr[0][2] = count;
// Traversing a two-dimensional array , Will not 0 Values are stored in a sparse array
// Record the number one 0 Elements
int k = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] != 0) {
k++;
sparseArr[k][0] = i;
sparseArr[k][1] = j;
sparseArr[k][2] = arr[i][j];
}
}
}
System.out.println(" Two dimensional array to sparse array :");
for (int i = 0; i < sparseArr.length; i++) {
System.out.printf("%d\t%d\t%d\t\n", sparseArr[i][0], sparseArr[i][1], sparseArr[i][2]);
}
System.out.println(" Sparse array to two-dimensional array :");
// Read the first line of the sparse array , And build the original two-dimensional array
int row = sparseArr[0][0];
int col = sparseArr[0][1];
int[][] arr2 = new int[row][col];
// Read the last few lines of sparse array data , And assign it to the original array
for (int i = 1; i < sparseArr.length; i++) {
arr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
}
for (int[] row2 : arr2) {
for (int item : row2) {
System.out.printf("%d\t", item);
}
System.out.println();
}
}
}