稀疏数组
介绍
当一个数组中大部分元素为0,或者为同一值的数组时,可研使用稀疏数组来保存该数组。
思路分析
- 记录数组一共有几行几列,有多少个不同的值。
- 把具有不同值的元素的行列及值记录在小规模的数组中,从而缩小程序的规模。
代码实现
public class SparseArray { public static void main(String[] args) { int chessOriginArr[][] = new int[11][11]; chessOriginArr[1][2]= 1; chessOriginArr[2][3]= 2; chessOriginArr[5][2]= 2; chessOriginArr[2][4]= 1; for(int[] row:chessOriginArr){ for(int data :row){ System.out.printf("%d\t",data); } System.out.println(); }
int count = 0; for(int[] row:chessOriginArr){ for(int data :row){ if(data!=0) { count++; } } } int sparseArr[][] = new int[count+1][3]; sparseArr[0][0] = 11; sparseArr[0][1] = 11; sparseArr[0][2] = count; int rowNum = 0; for (int i = 0; i < 11; i++) { for (int j = 0; j < 11; j++) { if(chessOriginArr[i][j]!=0){ rowNum++; sparseArr[rowNum][0] = i; sparseArr[rowNum][1] = j; sparseArr[rowNum][2] = chessOriginArr[i][j]; } } } System.out.println("------------------------------------"); for(int[] row:sparseArr){ for(int data :row){ System.out.printf("%d\t",data); } System.out.println(); } System.out.println("------------------------------------"); int chessOriginBackArr[][] = new int[sparseArr[0][0]][sparseArr[0][1]]; for (int i = 1; i < sparseArr.length; i++) { chessOriginBackArr[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2]; } for(int[] row:chessOriginBackArr){ for(int data :row){ System.out.printf("%d\t",data); } System.out.println(); } } }
|
输出结果:
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ------------------------------------ 11 11 4 1 2 1 2 3 2 2 4 1 5 2 2 ------------------------------------ 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
|