一,稀疏数组
稀疏数组可以看做是普通数组的压缩,但是这里说的普通数组是值无效数据量远大于有效数据量的数组
2.存储
刚说到稀疏数组是一种压缩后的数组,为什么要进行压缩存储呢?
[if !supportLists]· [endif]原数组中存在大量的无效数据,占据了大量的存储空间,真正有用的数据却少之又少
[if !supportLists]· [endif]压缩存储可以节省存储空间以避免资源的不必要的浪费,在数据序列化到磁盘时,压缩存储可以提高IO效率
3:二维数组转稀疏数组
思路:1:遍历二维数组了解数组中有效值个数sum
2:创建稀疏数组Arr[sum][3]
3:将数据存入稀疏数组第一列【row】【rol】[value]
/**
*初始化二维数组
*
* 0 0 0 0 0 0 0 0 0 0 0
* 0 0 1 0 0 0 0 0 0 0 0
* 0 0 0 0 2 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0 0 0 0
*
*/
//初始化原数组int[][] array = new int[11][11];
array[1][2] = 1;
array[2][4] = 2;
for
(int[] row : array){
for(int item : row){
System.
out.printf("%d\t",item);
}
System.
out.printf("\n");
}
System.
out.println("---------> 二维数组转稀疏数组");
/**
*稀疏数组
*
* 11 11 2
* 1 2 1
* 2 4 2
*
*/
//得到非0数据数int sum = 0;
for
(int i = 0;i<11;i++){
for(int j = 0;j<11;j++){
if(array[i][j] != 0){
sum++
;
}
}
}
//创建稀疏数组int[][] sparseArray = new int[sum+1][3];
//给稀疏数组赋值sparseArray[0][0] = 11;
sparseArray[0][1] = 11;
sparseArray[0][2] = sum;
//将非0的数放入稀疏数组
//count
:标识第几个非0数int count = 0;
for
(int i = 0;i<11;i++){
for(int j = 0;j<11;j++){
if(array[i][j] != 0){
count++
;
sparseArray[count][0] = i;
sparseArray[count][1] = j;
sparseArray[count][2] = array[i][j];
}
}
}
//遍历稀疏数组System.out.printf("列数 "+"行数 "+"值");
System.out.printf("\n");
for
(int i = 0;i<sparseArray.length;i++){
System.
out.printf("%d ,%d , %d\t",sparseArray[i][0],sparseArray[i][1],sparseArray[i][2]);
System.out.printf("\n");
}
System.
out.println("----------->稀疏数组转回原始数组");
4:稀疏数组转二维数组
1:因为稀疏数组第一列数据为行总数,列总数,有效数值
2:创建二维数组Arrilist[row][rol]
3:遍历稀疏数组赋值二维数组
int[][] oldArray = new int[sparseArray[0][0]][sparseArray[0][1]];
//将原来非0的数填充回去for(int i = 1;i<=count;i++){
oldArray[sparseArray[i][
0]][sparseArray[i][1]] = sparseArray[i][2];
}
//遍历刚转回的原始数组for(int[] row : oldArray){
for(int item : row){
System.
out.printf("%d\t",item);
}
System.
out.printf("\n");
}