稀疏数组

稀疏数组

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

稀疏数组的处理方式是:

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

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

如下图:左边为原始数组,右边是稀疏数组。

 

 

 

 

 程序代码:

package com.luckylu.array;

import java.util.Arrays;

public class ArrayDemo10 {
public static void main(String[] args) {
// 创建5*6 的二位数组 ; 0为没有其,1为黑棋,2为白棋
int[][] array1 = new int[5][6];
array1[1][2] = 1;
array1[2][3] = 2;
System.out.println("输出原始数组");

for (int[] rows: array1) { // 遍历二维数组的行 5行 增强for循环
for (int anInt: rows) { //遍历数值 增强for循环
System.out.print(anInt+"\t");
}
System.out.println(); // 输出5行
}

System.out.println("=================");
System.out.println("转换为稀疏数组:");
int sum = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 6; j++) {
if (array1[i][j]!=0){
sum++;
}

}
}

System.out.println("有效值的个数:"+sum);
//创建一个系数数组
int[][] array2 = new int[sum+1][3];
array2[0][0]=array1.length;
array2[0][1]=array1[0].length;
array2[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++;
array2[count][0]=i;
array2[count][1]=j;
array2[count][2]=array1[i][j];
}
}
}

for (int i = 0; i < array2.length; i++) {
System.out.println(array2[i][0]+"\t"+array2[i][1]+"\t"+array2[i][2]);
}

System.out.println("=================");
System.out.println("读取稀疏数组的值");
// 读取稀疏数组;定义二位数组的大小
int[][] array3 = new int[array2[0][0]][array2[0][1]];
//赋值

for (int i = 1; i <array2.length ; i++) {
array3[array2[i][0]][array2[i][1]] = array2[i][2];
}

// 打印
for (int[] rows: array3) { // 遍历二维数组的行 5行 增强for循环
for (int anInt: rows) { //遍历数值 增强for循环
System.out.print(anInt+"\t");
}
System.out.println(); // 输出5行
}

}
}

输出结果

 

posted @ 2022-03-06 15:06  luckylu1983  阅读(29)  评论(0)    收藏  举报