zoukankan      html  css  js  c++  java
  • 稀疏数组

    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();
        }
    }
    
  • 相关阅读:
    C语言I博客作业02
    第一次C语言作业
    C语言I博客作业02
    网页常用分享代码
    js生成验证码并验证
    js时间格式的转换
    Git 常用命令
    ASP.NET MVC中使用事务写法
    数据库游标导入数据
    js截取所需字符串长度
  • 原文地址:https://www.cnblogs.com/huacha/p/13941537.html
Copyright © 2011-2022 走看看