基本介绍
当一个数组中大部分元素为0,或者为同一个值的数组时,可以使用稀疏数组来保存该数组。
稀疏数组的处理方法是:
1)
记录数组一共有几行几列,有多少个不同的值
2)
把具有不同值的元素的行列及值记录在一个小规模的数组中,从而缩小程序的规模
稀疏数组举例说明
public class SparseArry {
public static void main(String[] args) {
// TODO Auto-generated method stub
int chessarry1[][] = new int[11][11];
int sum = 0,temp=0;
chessarry1[1][2] = 1;
chessarry1[2][3] = 2;
chessarry1[4][5] = 2;
System.out.println("初始数组");
for (int[] is : chessarry1) {
for (int data : is) {
if (data > 0) {
sum++;
}
System.out.printf("%d\t", data);
}
System.out.println();
}
System.out.println("存入稀疏数组");
System.out.println("有效数组总和" + sum);
int chessarry2[][] = new int[sum + 1][3];
chessarry2[0][0] = 11;
chessarry2[0][1] = 11;
chessarry2[0][2] = sum;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if(chessarry1[i][j]>0) {
chessarry2[++temp][0]=i;
chessarry2[temp][1]=j;
chessarry2[temp][2]=chessarry1[i][j];
}
}
}
System.out.println("---------稀疏数组---------");
for (int i = 0; i < sum+1; i++) {
for (int j = 0; j < 3; j++) {
System.out.printf("%d\t",chessarry2[i][j]);
}
System.out.println();
}
int chessarry [][]=new int[11][11];
for (int i = 1; i <=temp; i++) {
chessarry [chessarry2[i][0]][chessarry2[i][1]]=chessarry2[i][2];
}
System.out.println("---------转换后结果---------");
for (int[] is : chessarry) {
for (int data : is) {
System.out.printf("%d\t",data);
}
System.out.println();
}
}
}