总结:1创建原始数组(二维数组)
2提取二维数组中的有效值(非零的值或者相同的值)
3创建稀疏数组
4遍历稀疏数组,将有效值存放在稀疏数组中
public class arrayXS1 {
public static void main(String[] args) {
//第一步,输出原始数组
int[][] array1 = new int[11][11];
array1[0][1] = 1;
array1[1][1] = 2;
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array1[i].length; j++) {
System.out.print(array1[i][j]+"\t");
}
System.out.println();
}
//第二部,提取原始数组中的有效值
int sum = 0;
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array1[i].length; j++) {
if (array1[i][j]!=0){
sum++;
}
}
}
System.out.println("原始数组有效值个数:"+sum);
//第三步,创建稀疏数组
int[][] array2 = new int[sum+1][3];
array2[0][0] = 11;
array2[0][1] = 11;
array2[0][2] = sum;
//第四步,遍历稀疏数组,将非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++;
array2[count][0] = i;
array2[count][1] = j;
array2[count][2] = array1[i][j];
}
}
}
//第五步,输出稀疏数组
System.out.println("输出稀疏数组");
for (int[] i :array2){
for (int j:i){
System.out.print(j+"\t");
}
System.out.println();
}
//第六步,将稀疏数组还原成二维数组
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];
}
//第七步,输出还原之后的二维数组
for (int[] i :array3){
for (int j:i){
System.out.print(j+"\t");
}
System.out.println();
}
}
}