转换稀疏数组的简单使用

本文介绍了一种处理稀疏数组的方法,通过压缩减少存储空间,再通过还原算法恢复原始数据。具体实现了压缩和还原算法,并通过实例展示了过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

测试:转化 10*10 的稀疏数组

转化稀疏数组

    private static int[][] compressArray(int[][] resource) {
        int count = 0;
        for (int[] data : resource) {
            for (int d : data) {
                if (d != 0) count++;
            }
        }
        int[][] res = new int[count + 1][3];
        res[0][0] = 10;
        res[0][1] = 10;
        res[0][2] = count;
        count = 1;
        for (int i = 0; i < resource.length; i++) {
            for (int j = 0; j < resource[i].length; j++) {
                if (resource[i][j] != 0) {
                    res[count][0] = i;
                    res[count][1] = j;
                    res[count][2] = resource[i][j];
                    count++;
                }
            }
        }
        return res;
    }

恢复二维数组

 private static int[][] reductionArray(int[][] resource) {
        int[][] target = new int[resource[0][0]][resource[0][1]];
        for (int item = 1; item < resource.length; item++) {
            for (int it = 1; it < resource[item].length; it++) {
                target[resource[item][0]][resource[item][1]] = resource[item][2];
            }
        }
        return target;
    }

自定义输出语句

private static void myOut(int[][] resource) {
        for (int[] data : resource) {
            for (int item : data) {
                System.out.printf("%d\t", item);
            }
            System.out.println();
        }
    }

测试:

 public static void main(String[] args) {
        int[][] dates = new int[10][10];
        int[][] res;
        dates[1][2] = 1;
        dates[2][3] = 2;
      
        System.out.println("原始数据");
        myOut(dates);
        System.out.println("转换稀疏数组");
        res = compressArray(dates);
        myOut(res);
        System.out.println("还原稀疏数组");
        myOut(reductionArray(res));
    }

控制台结果

原始数据
0	0	0	0	0	0	0	0	0	0	
0	0	1	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	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	
转换稀疏数组
10	10	2	
1	2	1	
2	3	2	
将稀疏数组还原
0	0	0	0	0	0	0	0	0	0	
0	0	1	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	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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值