package com.wmx.sparsearray;
/**
* @Description 稀疏数组
* @Author 吴满心
* @Date 2022/9/12 7:36
* @Version 1.0
*/
public class SparseArray {
public static void main(String[] args) {
int[][] ints = new int[5][5];
ints[2][3] = 8;
ints[4][2] = 7;
int[][] sparseArr = toSparseArr(ints);
for (int[] ints1 : sparseArr) {
for (int i : ints1) {
System.out.printf("%d\t", i);
}
System.out.println();
}
int[][] originArr = fromSparseArr(sparseArr);
for (int[] ints1 : originArr) {
for (int i : ints1) {
System.out.printf("%d\t", i);
}
System.out.println();
}
}
public static int[][] toSparseArr(int[][] arr) {
int notNullCount = 0;
for (int[] ints : arr) {
for (int anInt : ints) {
if (anInt != 0) {
notNullCount++;
}
}
}
int[][] sparseArr = new int[notNullCount + 1][3];
sparseArr[0][0] = arr.length;
sparseArr[0][1] = arr[0].length;
sparseArr[0][2] = notNullCount;
int rowIndex = 1;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] != 0) {
sparseArr[rowIndex][0] = i;
sparseArr[rowIndex][1] = j;
sparseArr[rowIndex][2] = arr[i][j];
rowIndex++;
}
}
}
return sparseArr;
}
public static int[][] fromSparseArr(int[][] arr) {
int rowSize = arr[0][0];
int celSize = arr[0][1];
int notNullSize = arr[0][2];
int[][] ints = new int[rowSize][celSize];
for (int rowIndex = 1; rowIndex <= notNullSize; rowIndex++) {
int row = arr[rowIndex][0];
int cel = arr[rowIndex][1];
int value = arr[rowIndex][2];
ints[row][cel] = value;
}
return ints;
}
}
09-07
329
07-15
665
09-15
153