稀疏数组


稀疏数组

#当一个数组中大部分元素为同一值时的时候使用

#处理方式:

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