public class SparseArray01 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
int[][] test = {{0,1,0,4,0},{0,0,0,0,8},{9,0,0,2,6},{0,8,3,0,0,},{11,23,0,0,0}} ;
int[][] result = convertSparseArray(test);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src\\sparseArray.gxm"));
oos.writeObject(result);
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src\\sparseArray.gxm"));
int[][] result2 = convertCommonArray((int[][])ois.readObject());
for (int i = 0; i < result2.length ; i++) {
for (int j = 0; j < result2[i].length ; j++) {
System.out.print(result2[i][j] + "\t");
}
System.out.println();
}
}
public static int[][] convertSparseArray(int[][] commonArray){
int rows = commonArray.length;
// 取第一个一维数组的长度作为列数
int col = commonArray[0].length;
int notZeroNum = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < commonArray[i].length ; j++) {
if(commonArray[i][j] != 0){
notZeroNum++;
}
}
}
int[][] sparseArray = new int[notZeroNum + 1][3];
sparseArray[0][0] = rows;
sparseArray[0][1] = col;
sparseArray[0][2] = notZeroNum;
// 此变量用来标记稀疏数组的横坐标
int sparseArrayRow = 1;
// 从第二行开始给稀疏数组赋值
for (int i = 0; i < rows; i++) {
for (int j = 0; j < commonArray[i].length ; j++) {
int value = commonArray[i][j];
if(value != 0){
sparseArray[sparseArrayRow][0] = i;
sparseArray[sparseArrayRow][1] = j;
sparseArray[sparseArrayRow][2] = value ;
sparseArrayRow++;
}
}
}
return sparseArray;
}
public static int[][] convertCommonArray(int[][] sparseArray){
int row = sparseArray[0][0];
int col = sparseArray[0][1];
int[][] commonArray = new int[row][col];
// 默认是全零不用赋值了,java基础不行啊
// for (int i = 0; i < row; i++) {
// for (int j = 0; j < col; j++) {
// commonArray[i][j] = 0;
// }
// }
for (int i = 1; i < sparseArray.length ; i++) {
commonArray[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
}
return commonArray;
}
}
稀疏数组与普通数组互相转换
最新推荐文章于 2024-08-08 22:50:50 发布