【学习笔记】稀疏数组
稀疏数组的介绍
-
当一个数组中大部分元素为0时,或者为同一值的数据时,可以使用稀疏数组来保存该数组。
-
稀疏数组的处理方式是:
-
记录数组一共有几行几列,有多少个不同值
-
把具有不同值的元素和行列及值记录在一个小规模的数组中,从而缩小程序的规模
-
-
如下图,左边是原始数据,右边是稀疏数组
代码实现把原始数组压缩为稀疏数组
package com.wzt.array;
public class ArrayDemo05 {
public static void main(String[] args) {
int[][] array1 = new int[11][11];
array1[1][2] = 1;
array1[2][3] = 2;
for (int[] ints:array1) {
for (int anInt: ints) {
System.out.print(anInt + "\t");
}
System.out.println();
}
System.out.println("=========================");
//计算有值的元素的个数
int sum = 0;
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array1[i].length; j++) {
if (array1[i][j] != 0){
sum++;
}
}
}
System.out.println("有值的元素的个数为:" + sum);
System.out.println("=========================");
//构建稀疏数组
int[][] arrry2 = new int[sum+1][3];
arrry2[0][0] = 11;
arrry2[0][1] = 11;
arrry2[0][2] = sum;
//用来计数
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++;
arrry2[count][0] = i;
arrry2[count][1] = j;
arrry2[count][2] = array1[i][j];
}
}
}
//打印稀疏数组
for (int i = 0; i < arrry2.length; i++) {
for (int j = 0; j < arrry2[i].length; j++) {
System.out.print(arrry2[i][j] + "\t");
}
System.out.println();
}
还原稀疏数组:
//还原
int[][] array3 = new int[11][11];
for (int i = 1; i < arrry2.length; i++) {
array3[arrry2[i][0]][arrry2[i][1]] = arrry2[i][2];
}
System.out.println("还原");
for (int[] ints3: array3) {
for (int anInt3:ints3) {
System.out.print(anInt3 + "\t");
}
System.out.println();
}