WHCSRL 技术网

稀疏数组的理解

稀疏数组

稀疏数组就是一个二位数组chessArr有太多的废数据,就可以把有用的数据压缩一下,用一个新的二维数组来表示这些数据,这个新的二位数组以ans来表示

ans有很多的固有属性,就比如ans只有三列,并且在第一行中,第一列是chessArr的行数,第二列是chessArr的列数,第三列是有用数据的个数

其他行,第一列是该数据所在位置的行数,第二列是列数,第三列是具体的数据值

package com.Array;

public class Main {
  public static void main(String[] args) {
    int chessArr[][] = new int[11][11];
    chessArr[1][2] = 1;
    chessArr[2][3] = 2;
    for (int[] is : chessArr) {
      for(int data : is) {
        System.out.print(data);
        System.out.print('	');
      }
      System.out.println();
    }
    
    int sum = 0;
    for(int[] arr : chessArr) {
      for(int data : arr) {
        if(data != 0) {
          sum++;
        }
      }
    }
    
    int ans[][] = new int[sum+1][3];
    ans[0][0] = 11;
    ans[0][1] = 11;
    ans[0][2] = sum;
    int count = 1;
    for(int i = 0;i < 11;i++) {
      for(int j = 0;j < 11;j++) {
        if(chessArr[i][j] != 0) {
          ans[count][0] = i;
          ans[count][1] = j;
          ans[count][2] = chessArr[i][j];
          count++;
        }
      }
    }
    System.out.println("========================="+'
'+"稀疏数组为:");
    for(int[] arr : ans) {
      for(int data : arr) {
        System.out.print(data);
        System.out.print('	');
      }
      System.out.println();
    }
  }
}
  • 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

本周总结

本周主要还是学习数据结构,也开始写项目了,但是,数据结构依然没有学完,像搜索二叉树,还只是停留在表面,并没有深入地去了解过,希望下周在写项目的过程中还能够补充一下数据结构。

推荐阅读