当一个数组中大部分元素为0,或者为同一值的数组时,可以使用稀疏数组来保存该数组。
稀疏数组的处理方式是:
如下图:左边是原始数组,右边是稀疏数组
package com.guan.array; import java.util.Arrays; public class ArrayDemo08 { public static void main(String[] args) { int[][] array1 = new int[11][11]; array1[1][2] = 1; array1[2][3] = 1; //输出原始数组 System.out.println("输出原始数组"); for (int[] ints : array1) {//arrays.for外层输出 打印二维数组 for (int anInt : ints) {//ints.for内层循环 System.out.print(anInt+"\t"); } System.out.println(); } System.out.println("==============="); //转化为稀疏数组 //1。获取有效值的个数 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("sun = "+sum); System.out.println("==============="); //2。创建稀疏数组 int[][] arrary2 = new int[sum+1][3]; arrary2[0][0] = 11; arrary2[0][1]= 11; arrary2[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++; arrary2[count][0]= i; arrary2[count][1]= j; arrary2[count][2]= array1[i][j]; } } } for (int i = 0; i < arrary2.length; i++) { // System.out.println(arrary2[i][0]+"\t" // +arrary2[i][1]+"\t" // +arrary2[i][2]+"\t"); for (int j = 0; j < arrary2[i].length; j++) { System.out.print(arrary2[i][j]+"\t"); } System.out.println(); } //还原稀疏数组 System.out.println("============"); System.out.println("还原"); //1.读取稀疏数组 int[][] array3 = new int[arrary2[0][0]][arrary2[0][1]]; //.给其中元素还原值 for (int i = 1; i < arrary2.length; i++) { array3[arrary2[i][0]][arrary2[i][1]] = arrary2[i][2]; } //3.打印数组 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 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 =============== sun = 2 =============== 11 11 2 1 2 1 2 3 1 ============ 还原 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 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0