One, sparse array
1. Concept
When using a two-dimensional array to save data, if the number of saved non-default values (such as the default value of the int type is 0) is less than the size of the entire two-dimensional array , you can consider using a sparse array to reduce memory usage.
The first dimension is the sparse array normal array 一维长度
二维长度
and 非默认元素个数
; other non-default dimension element 一维下标
二维下标
and元素值
2. Conversion steps
1) Normal array to sparse array
- Get the one-dimensional and two-dimensional lengths of ordinary arrays, and the number of non-default elements
- Create a new sparse array (one-dimensional length is 1 + the number of non-default elements, two-dimensional length is 3)
- Traverse ordinary arrays and assign values to sparse arrays
2) Sparse array to ordinary array
- Get the first dimension of the sparse array, you can get the one-dimensional length of the ordinary array and the number of non-default elements with two-dimensional length
- Create a new ordinary array and initialize the default value
- Traverse the sparse array and assign non-default elements
3) Example
class SpareArray {
/**
* 将普通的二维数组转换为稀疏数组
*/
public static int[][] transform(int[][] array, int defaultValue) {
if (null == array) {
return null;
}
int len = array.length; // 一维长度
if (0 == len) {
return null;
}
int length = array[0].length; // 二维长度
if (0 == length) {
return null;
}
int count = 0;
for (int i = 0; i < len; i++) {
int[] arr = array[i];
for (int j = 0; j < length; j++) {
int ele = arr[j];
if (defaultValue != ele) {
count++;
}
}
}
int[][] spareArray = new int[1 + count][3];
spareArray[0][0] = len; // 一维长度
spareArray[0][1] = length; // 二维长度
spareArray[0][2] = count; // 非默认元素个数
int index = 0;
for (int a = 0; a < len; a++) {
for (int b = 0; b < length; b++) {
int ele = array[a][b];
if (defaultValue != ele) {
index++;
spareArray[index][0] = a;
spareArray[index][1] = b;
spareArray[index][2] = ele;
}
}
}
return spareArray;
}
/**
* 将稀疏数组恢复回普通的二维数组
*/
public static int[][] recover(int[][] spareArray, int defaultValue) {
if (null == spareArray) {
return null;
}
int len = spareArray[0][0];
int length = spareArray[0][1];
int count = spareArray[0][2];
int[][] array = new int[len][length];
for (int i = 0; i < len; i++) {
for (int j = 0; j < length; j++) {
array[i][j] = defaultValue;
}
}
for (int a = 1; a <= count; a++) {
// 从稀疏数组的第二维开始遍历
int x = spareArray[a][0];
int y = spareArray[a][1];
int ele = spareArray[a][2];
array[x][y] = ele;
}
return array;
}
}