稀疏数组
实际需求

使用二维数组记录会产生很多无意义的数据,上图的数组产生了很多的0
使用稀疏数组解决
- 记录数组一共有几行几列,有多少个不同的值
- 把具有不同值的元素的行列及值记录在一个小规模的数组中,从而缩小程序的规模


代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| package top.lcopilot.sparseArr; public class SparseArray { public static void main(String[] args) { int chessArr1[][] = new int[11][11]; chessArr1[1][2] = 1; chessArr1[2][3] = 2; System.out.println("原始的二维数组 : "); for(int[] row : chessArr1) { for(int data : row) { System.out.printf("%d\t", data); } System.out.println(); } int sum = 0; for(int i=0; i<chessArr1.length;i++) { for(int j=0;j<chessArr1[i].length;j++) { if(chessArr1[i][j] != 0) sum ++ ; } } int[][] sparseArr = new int[sum+1][3]; sparseArr[0][0] = chessArr1.length; sparseArr[0][1] = chessArr1[0].length; sparseArr[0][2] = sum; int count = 0; for(int i=0;i<chessArr1.length;i++) { for(int j=0;j<chessArr1[0].length;j++) { if(chessArr1[i][j] != 0) { count++ ; sparseArr[count][0] = i; sparseArr[count][1] = j; sparseArr[count][2] = chessArr1[i][j]; } } } System.out.println(); System.out.println("得到稀疏数组为: " ); for(int i=0; i<sparseArr.length;i++) { System.out.printf("%d\t%d\t%d\t\n", sparseArr[i][0], sparseArr[i][1], sparseArr[i][2]); } System.out.println(); int[][] chessArr2 = new int[sparseArr[0][0]][sparseArr[0][1]]; System.out.println(); System.out.println("恢复后的二维数组"); for(int i=1; i<sparseArr.length;i++) { chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2]; } for(int[] row : chessArr2) { for(int data : row) { System.out.printf("%d\t", data); } System.out.println(); } } }
|