其他分享
首页 > 其他分享> > 稀疏数组的读取与还原

稀疏数组的读取与还原

作者:互联网

public class Demo08 {
    public static void main(String[] args) {
        //创建一个10*10的二维数组,最终将该数组对应的稀疏数组打印出来
        int[][] array1 = new int[10][10];
        array1[2][3] = 2;
        array1[4][2] = 13;
        array1[3][6] = 25;

        //将二维数组打印出来
        for (int i = 0; i < array1.length; i++) {
            for (int j = 0; j < array1[i].length; j++) {
                System.out.print(array1[i][j]+" ");
            }
          System.out.println();
        }

        //获取稀疏数组的有效值个数
        int sum = 0;
        for (int i = 0; i < array1.length; i++) {
            for (int j = 0; j < array1[i].length; j++) {
                if (array1[i][j] != 0) {
                    sum+=1;
                }
            }
        }
        System.out.println("稀疏数组的有效个数sum值为"+sum);


        //创建一个(sum+1)*3的二维稀疏数组
        //****注意:稀疏数组第一行是(10,10,3):10*10的数组对应稀疏数组的行数为3
        int[][] array2 = new int[sum+1][3];
         array2[0][0] = 10;
         array2[0][1] = 10;
         array2[0][2] = sum;

         int der = 1;
        for (int i = 0; i < array1.length; i++) {
            for (int j = 0; j < array1[i].length; j++) {
                if (array1[i][j] !=0) {
                    array2[der][0] = i;
                    array2[der][1] = j;
                    array2[der][2] = array1[i][j];
                    der++;
                }
            }
        }
        //打印稀疏数组
        for (int i = 0; i < array2.length; i++) {
            System.out.println(array2[i][0]+" "+array2[i][1]
            +" "+array2[i][2]);
        }


        //1.读取稀疏数组
        //2.将稀疏数组还原

        //按照稀疏数组第一行的对应行、列的值创建一个新数组array3
        int[][] array3 = new int[array2[0][0]] [array2[0][1]];
        for (int i = 1; i < array2.length; i++) {
                    array3[array2[i][0]] [array2[i][1]] = array2[i][2];
        }
        //将还原的二维数组打印出来
        //(数组的默认值是0)+
           for (int i = 0; i < array3.length; i++) {
               for (int j = 0; j < array3[i].length; j++) {
                   System.out.print(array3[i][j]+" ");
               }
             System.out.println();
           }
    }
}

 

标签:10,读取,int,array2,array1,稀疏,++,数组
来源: https://www.cnblogs.com/Hangli123/p/16216365.html