當一個數(shù)組的元素包含大量的0時,或者為同一個值的數(shù)組時,可以使用稀疏數(shù)組來保存數(shù)組.
稀疏數(shù)組的處理方法:
1,記錄數(shù)組一共有幾行幾列,有多少個不同的值
2,把具有不同值的元素的行列及值記錄在一個小規(guī)模的數(shù)組(稀疏數(shù)組)中,從而縮小程序的規(guī)
實例講解:
圖片中的二維數(shù)組轉換成稀疏數(shù)組
publicclassSparesArry{
?
? ? publicstaticvoidmain(String[]args) {
?
? ? ? ? intchessArry1[][]=newint[11][11];
?
? ? ? ? chessArry1[1][2]=1;
?
? ? ? ? chessArry1[2][3]=2;
?
? ? ? ? for(int[]arr:chessArry1) {
?
? ? ? ? ? ? for(intdata:arr) {
?
? ? ? ? ? ? ? ? System.out.printf("%d\t",data);
?
? ? ? ? ? ? }
?
? ? ? ? ? ? System.out.println();
?
? ? ? ? }
?
? ? ? ? // 原始二維數(shù)組
?
? ? ? ? intsum=0;
?
? ? ? ? for(inti=0;i<chessArry1.length;i++) {
?
? ? ? ? ? ? for(intj=0;j<chessArry1.length;j++) {
?
? ? ? ? ? ? ? ? if(chessArry1[i][j]!=0) {
?
? ? ? ? ? ? ? ? ? ? sum++;
?
? ? ? ? ? ? ? ? }
?
? ? ? ? ? ? }
?
? ? ? ? }
?
? ? ? ? // 遍歷原始數(shù)組統(tǒng)計數(shù)值
?
? ? ? ? intsparesarry[][]=newint[sum+1][3];
?
? ? ? ? sparesarry[0][0]=11;// 行數(shù)
?
? ? ? ? sparesarry[0][1]=11;// 列數(shù)
?
? ? ? ? sparesarry[0][2]=sum;// 統(tǒng)計數(shù)
?
? ? ? ? // 遍歷數(shù)組存值,講原數(shù)組信息存貯到稀疏數(shù)組里
?
? ? ? ? intcount=0;
?
? ? ? ? for(inti=0;i<chessArry1.length;i++) {
?
? ? ? ? ? ? for(intj=0;j<chessArry1.length;j++) {
?
? ? ? ? ? ? ? ? if(chessArry1[i][j]!=0) {
?
? ? ? ? ? ? ? ? ? ? count++;
?
? ? ? ? ? ? ? ? ? ? sparesarry[count][0]=i;
?
? ? ? ? ? ? ? ? ? ? sparesarry[count][1]=j;
?
? ? ? ? ? ? ? ? ? ? sparesarry[count][2]=chessArry1[i][j];
?
? ? ? ? ? ? ? ? }
?
? ? ? ? ? ? }
?
? ? ? ? }
?
? ? ? ? System.out.println();
?
? ? ? ? // 打印稀疏數(shù)組
?
? ? ? ? for(intc=0;c<sparesarry.length;c++) {
?
? ? ? ? ? ? System.out.printf("%d\t%d\t%d\t\n",sparesarry[c][0],sparesarry[c][1],sparesarry[c][2]);
?
? ? ? ? }
?
? ? ? ? System.out.println();
?
? ? ? ? // 將稀疏數(shù)組還原成原數(shù)組
?
? ? ? ? // 1.先讀取稀疏數(shù)組第一行,根據(jù)第一行數(shù)據(jù)信息,創(chuàng)建出二維數(shù)組
?
? ? ? ? // 2/讀取稀疏數(shù)組后面幾行,并將數(shù)據(jù)添加到二維數(shù)組中
?
? ? ? ? intchessArry2[][]=newint[sparesarry[0][0]][sparesarry[0][1]];
?
? ? ? ? for(inti=1;i<sparesarry.length;i++) {// 從第二行開始讀取數(shù)據(jù)
?
? ? ? ? ? ? chessArry2[sparesarry[i][0]][sparesarry[i][1]]=sparesarry[i][2];
? ? ? ? }
? ? ? ? System.out.println();
?
? ? ? ? for(int[]arr:chessArry2) {
? ? ? ? ? ? for(intdata:arr) {
? ? ? ? ? ? ? ? System.out.printf("%d\t",data);
? ? ? ? ? ? }
? ? ? ? ? ? System.out.println();
? ? ? ? }
? ? }
}
?