1.稀疏数组
//稀疏数组
int[][] array1=new int[11][11];
array1[4][5]=68;
array1[3][2]=73;
array1[5][5]=62;
array1[7][9]=78;
array1[1][4]=56;
array1[2][4]=32;
array1[2][6]=26;
array1[2][1]=23;
array1[5][1]=22;
for (int[] ints : array1) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}
/*控制台输出
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 56 0 0 0 0 0 0
0 23 0 0 32 0 26 0 0 0 0
0 0 73 0 0 0 0 0 0 0 0
0 0 0 0 0 68 0 0 0 0 0
0 22 0 0 0 62 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 78 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 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++;
}
}
}
int[][] array2=new int[count+1][3];
array2[0][0]=11;
array2[0][1]=11;
array2[0][2]=count;
int count2=0;
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array1[i].length; j++) {
if (array1[i][j]!=0){//如果数组不等于0的话,i相当于横坐标,j相当于纵坐标,array1[i][j]是值
count2++;
array2[count2][0]=i;
array2[count2][1]=j;
array2[count2][2]=array1[i][j];
}
}
}
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();
}
/*输出结果为
11 11 9
1 4 56
2 1 23
2 4 32
2 6 26
3 2 73
4 5 68
5 1 22
5 5 62
7 9 78
*/
2.稀疏数组还原
//稀疏数组还原
int row=(int) array2[0][0];
int column=array2[0][1];
int[][] array3=new int[row][column];
/* for (int[] ints : array3) {
for (int anInt : ints) {
System.out.print(anInt+" ");
}
System.out.println();
}*/
for (int i = 1; i < array2.length-1; i++) {//循环遍历还原,原数组
array3[array2[i][0]][array2[i][1]]=array2[i][2];
if (array2.length-2==i){//最后一个因为稀疏数组之前加一,所以会超出,这里需要判断一下是否是最后一个
array3[array2[i+1][0]][array2[i+1][1]]=array2[i+1][2];
}
}
for (int i = 0; i < array3.length ; i++) {
for (int j = 0; j < array3[i].length; j++) {
System.out.print(array3[i][j]+"\t");
}
System.out.println();
}
/*输出结果
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 56 0 0 0 0 0 0
0 23 0 0 32 0 26 0 0 0 0
0 0 73 0 0 0 0 0 0 0 0
0 0 0 0 0 68 0 0 0 0 0
0 22 0 0 0 62 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 78 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
*/
}