public class ArrayDemo {
public static void main(String[] args) {
int[][] commonArray = new int[11][10];
commonArray[3][4] = 1;
commonArray[4][5] = 2;
for (int[] row : commonArray) {
for (int value : row) {
System.out.print(" " + value + " ");
}
System.out.println();
}
toSparseArray(commonArray);
}
private static void toSparseArray(int[][] commonArray) {
System.out.println("=============拿到一个二维数组开始进行转换");
if (commonArray != null && commonArray.length != 0){
int row = commonArray.length;
if (commonArray[0] != null){
int col = commonArray[0].length;
int sum = 0;
for (int[] commonRow : commonArray) {
for (int value : commonRow) {
if (value != 0){
sum++;
}
}
}
int[][] sparseArray = new int[sum+1][3];
sparseArray[0][0] = row;
sparseArray[0][1] = col;
sparseArray[0][2] = sum;
int sparseRow = 0;
sparseRow ++;
for (int i = 0; i < commonArray.length; i++) {
for (int j = 0; j < commonArray[i].length; j++) {
if (commonArray[i][j] != 0){
sparseArray[sparseRow][0] = i;
sparseArray[sparseRow][1] = j;
sparseArray[sparseRow][2] = commonArray[i][j];
sparseRow ++;
}
}
}
for (int[] newRow1 : sparseArray) {
for (int i : newRow1) {
System.out.print(" " + i + " ");
}
System.out.println();
}
toReverse(sparseArray);
}
}
}
private static void toReverse(int[][] array) {
System.out.println("================从一个稀疏数组还原成普通数组");
int[][] reArray = new int[array[0][0]][array[0][1]];
for (int i = 1; i < array.length; i++) {
reArray[array[i][0]][array[i][1]] = array[i][2];
}
for (int[] row : reArray) {
for (int value : row) {
System.out.print(" " + value + " ");
}
System.out.println();
}
}
}
稀疏数组学习小demo
最新推荐文章于 2023-01-07 12:11:42 发布