Java 稀疏数组
- 当一个数组中大部分元素为0,或者为同一值的数组时,可以使用稀疏数组来保存该数组。
示例:
package com.shun.array;
public class ArrayDemo08 {
public static void main(String[] args) {
//稀疏数组
//创建一个二维数组 11*11的棋盘格 0:代表没有棋子 1:黑棋 2:白棋
int[][] array1 = new int[11][11];
array1[1][2] = 1;
array1[2][3] = 2;
System.out.println("输出原始的数组");
for (int[] ints : array1) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}//输出的结果为:
//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("---------------------------");
//转化为稀疏数组保存
//1.先获取有效值的个数
int sum = 0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (array1[i][j]!=0){
sum++;
}
}
}
System.out.println("有效值的个数:"+sum);
//2.创建一个稀疏数组,并把第一行的值存放进去
int[][] array2 =new int[sum+1][3];
array2[0][0] = 11;
array2[0][1] = 11;
array2[0][2] = sum;
//3.把非零的值,存放到稀疏数组中去
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];
}
}
}
System.out.println("---------------");
//4.输出稀疏数组
System.out.println("稀疏数组");
for (int[] ints : array2) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}//输出的结果为:
//11 11 2
//1 2 1
//2 3 2
//还原稀疏数组
//1.创建数组
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];
}
//打印值
System.out.println("------------------");
System.out.println("输出还原数组:");
for (int[] ints : array3) {
for (int anInt : ints) {
System.out.print(anInt +"\t");
}
System.out.println();
}//输出的结果为:
//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
}
}