稀疏数组
1、稀疏数组的代码实现
@Test
public void test1() {
int[][] num = new int[6][7];
int count = 0; //记录不同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; //8个不同值
//再放不为0的数
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; //0号位为行号
sparseArray[countNum1][1] = j; //1号位为列号
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("");
}
}