稀疏数组
package array;
import java.util.Arrays;
public class Sparse {
public static void main(String[] args) {
//创建二维数组
System.out.println("遍历原数组:");
int[][] arrays1 = new int[11][11];
arrays1[1][2] = 1;
arrays1[2][3] = 2;
for (int[] ints : arrays1) {
for (int anInt : ints) {
System.out.print(anInt+" ");
}
System.out.println();
}
//转化为稀疏数组
//计算有效值个数
int sum = 0;
for (int i = 0; i < arrays1.length; i++) {
for (int j = 0; j < arrays1[i].length; j++) {
if(arrays1[i][j] != 0){
++sum;
}
}
}
System.out.println("有效值个数为:"+sum);
//创建稀疏数组
int[][] arrays2 = new int[sum+1][3];//sum+1是为了增加头部显示行、列、值的个数综合;3是为了表示有效值和对应的坐标
arrays2[0][0] = arrays1.length;
arrays2[0][1] = arrays1[1].length;
arrays2[0][2] = sum;
int temp = 1;//用于计算储存的数据下标
for (int i = 0; i < arrays1.length; i++) {
for (int j = 0; j < arrays1[i].length; j++) {
if(arrays1[i][j] != 0){
arrays2[temp][2] = arrays1[i][j];
arrays2[temp][1] = j;
arrays2[temp][0] = i;
++temp;
}
}
}
System.out.println("遍历稀疏数组:");
//遍历稀疏数组
for (int i = 0; i < arrays2.length; i++) {
for (int j = 0; j < arrays2[i].length; j++) {
System.out.print(arrays2[i][j]+" ");
}
System.out.println();
}
//将稀疏数组还原为原数组
int[][] arrays3 = new int[arrays2[0][0]][arrays2[0][1]];
for (int i = 1; i < arrays2.length; i++) {
arrays3[arrays2[i][0]][arrays2[i][1]] = arrays2[i][2];
}
System.out.println("遍历解析后的数组:");
for (int[] ints : arrays3) {
for (int anInt : ints) {
System.out.print(anInt+" ");
}
System.out.println();
}
}
}
标签:int,System,稀疏,++,数组,out,arrays1,arrays2
From: https://www.cnblogs.com/qt0312/p/16747246.html