稀疏数组与普通数组互相转换

public class SparseArray01 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        int[][] test = {{0,1,0,4,0},{0,0,0,0,8},{9,0,0,2,6},{0,8,3,0,0,},{11,23,0,0,0}} ;
        int[][] result = convertSparseArray(test);
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src\\sparseArray.gxm"));
        oos.writeObject(result);
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src\\sparseArray.gxm"));
        int[][] result2 = convertCommonArray((int[][])ois.readObject());
        for (int i = 0; i < result2.length ; i++) {
            for (int j = 0; j < result2[i].length  ; j++) {
                System.out.print(result2[i][j] + "\t");
            }
            System.out.println();
        }


    }
    public static int[][] convertSparseArray(int[][] commonArray){
        int rows  = commonArray.length;
//        取第一个一维数组的长度作为列数
        int col = commonArray[0].length;
        int notZeroNum = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < commonArray[i].length ; j++) {
                if(commonArray[i][j] != 0){
                    notZeroNum++;
                }
            }
        }
        int[][] sparseArray = new int[notZeroNum + 1][3];
        sparseArray[0][0] = rows;
        sparseArray[0][1] = col;
        sparseArray[0][2] = notZeroNum;
//        此变量用来标记稀疏数组的横坐标
        int sparseArrayRow = 1;
//        从第二行开始给稀疏数组赋值
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < commonArray[i].length ; j++) {
                int value = commonArray[i][j];
                if(value != 0){
                    sparseArray[sparseArrayRow][0] = i;
                    sparseArray[sparseArrayRow][1] = j;
                    sparseArray[sparseArrayRow][2] = value ;
                    sparseArrayRow++;
                }
            }
        }
        return sparseArray;

    }
    public static int[][] convertCommonArray(int[][] sparseArray){
        int row = sparseArray[0][0];
        int col = sparseArray[0][1];
        int[][] commonArray = new int[row][col];
//        默认是全零不用赋值了,java基础不行啊
//        for (int i = 0; i < row; i++) {
//            for (int j = 0; j < col; j++) {
//                commonArray[i][j] = 0;
//            }
//        }
        for (int i = 1; i < sparseArray.length ; i++) {
            commonArray[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
        }
        return commonArray;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值