其他分享
首页 > 其他分享> > 稀疏数组的创建和复原

稀疏数组的创建和复原

作者:互联网

包位置、主类代码框架已删方便你取走运行

在这里插入图片描述




    public static void main(String[] args) {
        int[][] Array = new int[12][12];
        Array[6][6] = 1;
        Array[8][6] = 7;
        for (int[] array : Array)
        {
            System.out.println(Arrays.toString(array));
        }
        System.out.println();
        int sum=0;
        for (int i = 0; i < Array.length; i++)
        {
            for (int j = 0; j < Array[i].length; j++)
            {
                if (Array[i][j] != 0)
                {
                    sum++;
                }
            }
        }
        int[][] Array1 = new int[sum+1][3];
        Array1[0][0] = Array.length;
        Array1[0][1] = Array[0].length;
        Array1[0][2] = sum;
        int count=0;
        for (int i = 0; i < Array.length; i++)
        {
            for (int j = 0; j < Array[i].length; j++)
            {
                if (Array[i][j]!=0)
                {
                    count++;
                    Array1[count][0] = i;
                    Array1[count][1] = j;
                    Array1[count][2] = Array[i][j];


                }
            }
        }
        for (int[] array1 : Array1)
        {
            System.out.println(Arrays.toString(array1));
        }
        System.out.println();
        int[][] Array2 = new int[Array1[0][0]][Array1[0][1]];
        for (int i = 1; i < Array.length; i++)
        {
            Array2[Array1[i][0]][Array1[i][1]]=Array1[i][2];
        }


        for (int[] array2 : Array2)
        {
            System.out.println(Arrays.toString(array2));
        }



    }




在这里插入图片描述

标签:int,Array1,稀疏,++,length,数组,Array,复原,out
来源: https://blog.csdn.net/weixin_43791695/article/details/116566785