ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

稀疏数组

2021-10-30 09:00:21  阅读:184  来源: 互联网

标签:数组 normal int 稀疏 ++ length sparse


稀疏数组

学习就了如果累了,就休息一下,不要疲劳学习,效果不好,要永远对知识充满渴望

/*
  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
 */

形如上面的一个11*11的数组,仅两位值不为0,其余值均为0,存储为数组占用空间,为了压缩空间,节约成本,可以将其压缩为稀疏数组

稀疏数组:

当一个数组中大部分元素为0,或者为同一值,就可以使用稀疏数组来保存该数组

稀疏数组的处理方式

1.记录数组一共有几行几列,有多少个不同值

2.把具有不同值的元素行列及值记录在一个小规模的数组中,从而缩小程序的规模

原始数组及稀疏数组

/* 
  原始数组                              稀疏数组
                                      行   列   值  
  0 0 0 0 0 0 0 0 0 0 0           [0] 11  11   2
  0 0 1 0 0 0 0 0 0 0 0           [1]  1   2   1
  0 0 0 2 0 0 0 0 0 0 0           [2]  2   3   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
 */

原始数组转稀疏数组

public static int[][] normalToSparse(int[][] normal) {
    int sum = 0;
    for (int i = 0; i < normal.length; i++) {
        for (int j = 0; j < normal[0].length; j++) {
            if (normal[i][j] != 0) {
                sum++;
            }
        }
    }

    int[][] sparse = new int[sum + 1][3];
    sparse[0][0] = normal.length;
    sparse[0][1] = normal[0].length;
    sparse[0][2] = sum;

    int count = 0;
    for (int i = 0; i < normal.length; i++) {
        for (int j = 0; j < normal[0].length; j++) {
            if (normal[i][j] != 0) {
                count++;
                sparse[count][0] = i;
                sparse[count][1] = j;
                sparse[count][2] = normal[i][j];
            }
        }
    }
    for (int i = 0; i < sparse.length; i++) {
        System.out.println(sparse[i][0] + " " + sparse[i][1] + " " + sparse[i][2]);
    }
    return sparse;

}

稀疏数组转原始数组

public static int[][] sparseToNormal(int[][] sparse) {
    int[][] normal = new int[sparse[0][0]][sparse[0][1]];
    for (int i = 1; i <= sparse[0][2]; i++) {
        normal[sparse[i][0]][sparse[i][1]] = sparse[i][2];

    }

    for (int i = 0; i < normal.length; i++) {
        System.out.println(Arrays.toString(normal[i]));
    }
    return normal;

}

标签:数组,normal,int,稀疏,++,length,sparse
来源: https://www.cnblogs.com/Oh-mydream/p/15484275.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有