其他分享
首页 > 其他分享> > 稀疏数组

稀疏数组

作者:互联网

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]);
        }
    }
}

 

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