• 稀疏数组


    public static void main(String[] args) {
    
        int[][] array1 = new int[11][11];
        array1[1][2]=1;
        array1[2][3] = 2;
        printArray(array1);
        /*
        0  0  0  0  0  0  0  0  0  0  0
        0  0  1  0  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  0  0  0  0  0  0  0  0
        0  0  0  0  0  0  0  0  0  0  0
         */
        System.out.println("==========================");
        int count = 0;
        //计算稀疏数组有效值个数
        for (int i = 0; i < array1.length; i++) {
            for (int j = 0; j < array1[i].length; j++) {
                if(array1[i][j]!=0)
                {
                    count++;
                }
            }
        }
        int[][] zipArray = new int[count+1][3];
        //稀疏数组第一行保存数组 行数 列数 有效值(不等于0)个数
        zipArray[0][0] = array1.length;
        zipArray[0][1] = array1[0].length;//最前面得判断是否有数据,这里偷懒了
        zipArray[0][2] = count;
    
        int zipRow = 1;//zipArray第二行开始,下标是1
        for (int i = 0; i < array1.length; i++) {
            for (int j = 0; j < array1[i].length; j++) {
                if(array1[i][j]!=0)
                {
                    //记录原数组,数据坐标
                    zipArray[zipRow][0]=i;
                    zipArray[zipRow][1]=j;
                    zipArray[zipRow][2]=array1[i][j];
                    zipRow++;
                }
            }
        }
        printArray(zipArray);
        System.out.println("==========================");//数组转稀疏数组完成
        //稀疏数组转原数组
        int[][] unZipArray = new int[zipArray[0][0]][zipArray[0][1]];
        for (int i = 1; i < zipArray.length; i++) {
            unZipArray[zipArray[i][0]][zipArray[i][1]] = zipArray[i][2];
        }
        printArray(unZipArray);
    
    
    }
    
    private static void printArray(int[][] array)
    {
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                System.out.print(array[i][j]+"	");
            }
            System.out.println();
        }
    }
    
  • 相关阅读:
    dstat
    centos安装指定版本的golang
    APP防CC为什么复杂
    火狐浏览器的书签如何自动在新窗口打开?
    linux jdk版本随时切换
    centos7 yum安装java环境
    kangle清除缓存接口
    CC攻击原理及防范方法
    GET 和 POST 的区别 以及为什么 GET请求 比 POST请求 更快
    HTTP缓存机制
  • 原文地址:https://www.cnblogs.com/huacha/p/13941537.html
Copyright © 2020-2023  润新知