二维数组转换为稀疏数组代码实现

实现方式代码如下:

package com.liu.sparse;

/**
 * 二维数组转换为稀疏数组案例
 */
public class SparseArray {
    public static void main(String[] args) {
        //创建二维数组
        int array[][] = new int[11][11];
        //赋值
        array[1][1] = 1;
        array[2][2] = 2;
        array[3][3] = 3;
        //遍历
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                System.out.print(array[i][j] + "  ");
            }
            System.out.println();
        }
        int sum = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (array[i][j] != 0 ){
                    sum++;
                }
            }
        }
        int arr[][] = new int[sum+1][3];
        arr[0][0] = 11;
        arr[0][1] = 11;
        arr[0][2] = sum;
        int index = 1;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (array[i][j] != 0) {
                    arr[index][0] = i;
                    arr[index][1] = j;
                    arr[index][2] = array[i][j];
                    index++;
                }
            }
        }
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(arr[i][j] + "  ");
            }
            System.out.println();
        }
    }
}

效果:

原数组:

 

 稀疏数组:

 

posted @ 2022-07-09 11:03  努力学习の小白  阅读(16)  评论(0编辑  收藏  举报
Live2D