简介
如果一个数组大部分的值是默认值,且数组较大时,可以使用稀疏数组来保存该数组,可以有效节省资源
算法
如图,把左边的数组精简成只记录有效值的数组,第一列记录行数,列数,有效值个数,后面的列记录有效值行下标,列下标,有效值
实现方法
public class SparseArray {
public static void main(String[] args) {
int[][] array = new int[10][10];
array[1][1] = 1;
array[2][2] = 2;
printArray(array);
int[][] sparseArray = toSparseArray(array);
printArray(sparseArray);
int[][] reductionArray = toArray(sparseArray);
printArray(reductionArray);
}
static void printArray(int[][] array) {
for (int[] ints : array) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println("\t");
}
}
static int[][] toSparseArray(int[][] array) {
int[][] sparseArray = creatSparseArray(getEffectiveNum(array), array.length, array[0].length);
int count = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
if (array[i][j] != 0) {
count++;
sparseArray[count][0] = i;
sparseArray[count][1] = j;
sparseArray[count][2] = array[i][j];
}
}
}
return sparseArray;
}
static int getEffectiveNum(int[][] array) {
int num = 0;
for (int[] ints : array) {
for (int anInt : ints) {
if (anInt != 0) {
num++;
}
}
}
return num;
}
static int[][] creatSparseArray(int EffectiveNum, int i, int j) {
int[][] array = new int[EffectiveNum+1][3];
array[0][0] = i;
array[0][1] = j;
array[0][2] = EffectiveNum;
return array;
}
static int[][] toArray(int[][] sparseArray) {
int[][] array = new int[sparseArray[0][0]][sparseArray[0][1]];
for (int i = 0; i < sparseArray[0][2]; i++) {
array[sparseArray[i+1][0]][sparseArray[i+1][1]] = sparseArray[i+1][2];
}
return array;
}
}