稀疏數組


稀疏數組

#當一個數組中大部分元素為同一值時的時候使用

#處理方式:

1.記錄數組一共有幾行幾列,有多少個不同的值

2.把不同值的元素和行列以及值記錄在小規模的一個數組中

3.稀疏數組占用內存小,減少IO的運算時間增加效率

public class AaaayDome08 {
  public static void main(String[] args) {
      //創建一個原始二維數組 11*11 0:沒有棋子 1:黑棋 2:白棋
      int[][] arrays = new int[11][11];
      arrays[1][2]= 1;
      arrays[2][4]= 2;
      arrays[5][4]= 1;
      arrays[6][7]= 2;

      //輸出原始數組
      for (int[] ints : arrays) {
          for (int anInt : ints) {
              System.out.print(anInt+"\t");
          }
          System.out.println();
      }
      //轉換為稀疏數組保存並獲取有效值的個數
      int sum = 0;
      for (int i = 0; i < arrays.length; i++) {
          for (int j = 0; j < arrays[i].length; j++) {
              if (arrays[i][j]!=0){
                  sum++;
              }
          }
      }
      System.out.println("有效值的個數為:"+sum);
      //創建一個稀疏數組的數組、打印出表頭
      int[][] arrays2 = new int[sum+1][3];
      arrays2[0][0]= 11;
      arrays2[0][1]= 11;
      arrays2[0][2]= sum;
      //sum+1:sum是有效值的多少就打印多少行,+1是第一行是要打印行、列、值
      //3列是固定的

      //遍歷二維數組,將非零的值,存放在稀疏數組中
      //count代表非0的數
      int count = 0;
      for (int i = 0; i < arrays.length; i++) {
          for (int j = 0; j < arrays[i].length; j++) {
              if (arrays[i][j]!=0){
                  count++;
                  arrays2[count][0]=i;//行
                  arrays2[count][1]=j;//列
                  arrays2[count][2]=arrays[i][j];//值
              }
          }
      }
      //輸出稀疏數組
      for (int[] ints : arrays2) {
          for (int anInt : ints) {
              System.out.print(anInt+"\t");
          }
          System.out.println();
      }
      //還原稀疏數組
      // 1.先創建一個新數組來讀取稀疏數組
      int[][] arrays3 = new int[11][11];
      //2.給其中的元素還原它的值
      for (int i = 1; i < arrays2.length; i++) {
          arrays3[arrays2[i][0]][arrays2[i][1]]= arrays2[i][2];
      }
      //打印還原的數組
      for (int[] ints : arrays3) {
          for (int anInt : ints) {
              System.out.print(anInt+"\t");
          }
          System.out.println();
      }
  }
}
//D:\Java\jdk1.8.0\bin\java.exe
//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 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 1 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
//有效值的個數為:4
//11  11 4
//1    2 1
//2    4 2
//5    4 1
//6    7 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 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 1 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
//
//Process finished with exit code 0


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM