稀疏数组
1、稀疏数组的代码实现
@Test
public void test1() {
int[][] num = new int[6][7];
int count = 0;
num[0][3] = 22;
num[0][6] = 15;
num[1][1] = 11;
num[1][5] = 17;
num[2][3] = -6;
num[3][5] = 39;
num[4][0] = 91;
num[5][2] = 28;
System.out.println("======================普通数组=============================");
for (int[] i : num) {
for (int j : i) {
if (j != 0) {
count++;
}
System.out.printf("%d\t",j);
}
System.out.println("");
}
System.out.println("======================稀疏数组=============================");
int[][] sparseArray = new int[count+1][3];
int countNum1 = 1;
sparseArray[0][0] = num.length;
sparseArray[0][1] = num[0].length;
sparseArray[0][2] = count;
for (int i = 0;i<num.length;i++) {
for (int j = 0;j<num[0].length;j++) {
if (num[i][j] != 0) {
sparseArray[countNum1][0] = i;
sparseArray[countNum1][1] = j;
sparseArray[countNum1][2] = num[i][j];
countNum1++;
}
}
}
for (int[] i : sparseArray) {
for (int j : i) {
System.out.printf("%d\t",j);
}
System.out.println("");
}
System.out.println("=====================恢复后的普通数组==============================");
int[][] num1 = new int[sparseArray[0][0]][sparseArray[0][1]];
for (int i = 1 ;i<sparseArray.length;i++) {
for (int j = 0;j<sparseArray[0].length;j++) {
num1[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][j];
}
}
for (int[] i : num1) {
for (int j : i) {
System.out.printf("%d\t",j);
}
System.out.println("");
}
}