稀疏数组
- 当一个数组中大部分元素为0,或者为同一值的数组时,可以使用稀疏数组来保存数组。
- 稀疏数组的处理方式是:
- 记录数组一共有几行几列,有多少个不同值
- 把具有不同值的元素和行列及值记录在一个小规模的数组中,从而缩小程序的规模
- 如下图:左边是原始数组,右边是稀疏数组。
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210522002018780.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xsbjE1NDAyOTU0NTk=,size_16,color_FFFFFF,t_70)
import java.util.Arrays;
public class Demo021 {
public static void main(String[] args) {
int[][] array1 = new int[11][11];
array1[1][2] = 1;
array1[2][3] = 2;
System.out.println("输出原始数组(棋盘样式):");
chessBoard(array1);
int[][] array2 = transform(array1);
printlnXiShu(array2);
int[][] array3 = transformBack(array2);
System.out.println("输出还原数组(棋盘样式):");
chessBoard(array3);
}
public static void chessBoard(int[][] array){
for(int[] i:array){
for(int j:i){
System.out.print(j+"\t");
}
System.out.println();
}
}
public static int[][] transform(int[][] array1){
int sum = getSum(array1);
int[][] array2 = new int[sum+1][3];
array2[0][0] = 11;
array2[0][1] = 11;
array2[0][2] = sum;
int count = 0;
for(int i=0;i<array1.length;i++){
for(int j=0;j<array1[i].length;j++){
if(array1[i][j]!=0){
count++;
array2[count][0] = i;
array2[count][1] = j;
array2[count][2] = array1[i][j];
}
}
}
return array2;
}
public static int getSum(int[][] array){
int sum =0;
for(int i=0;i<array.length;i++){
for(int j=0;j<array[i].length;j++){
if(array[i][j]!=0){
sum++;
}
}
}
System.out.println("有效值的个数为:" + sum);
return sum;
}
public static void printlnXiShu(int[][] array2){
System.out.println("稀疏数组:");
for(int i=0;i<array2.length;i++){
for(int j=0;j<array2[i].length;j++){
System.out.print(array2[i][j] +"\t");
}
System.out.println();
}
}
public static int[][] transformBack(int[][] array2){
int[][] array3 = new int[array2[0][0]][array2[0][1]];
for(int i=1;i<array2.length;i++){
array3[array2[i][0]][array2[i][1]] = array2[i][2];
}
return array3;
}
}
输出结果:
输出原始数组(棋盘样式):
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 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 0
有效值的个数为:2
稀疏数组:
11 11 2
1 2 1
2 3 2
输出还原数组(棋盘样式):
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 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 0