基本介绍
当一个数组中大部分元素为0,或者为同一个值的数组时,可以使用稀疏数组来保存该数组。节约空间
稀疏数组的处理方法是:
1.记录数组一共有几行几列,有多少个不同的值
2.把具有不同值的元素的行列及值记录在一个小规模的数组中,从而缩小程序的规模
二维数组转稀疏数组的思路
1.遍历二维数组,得到有效个数sum。
2.根据sum就可以创建稀疏数组sparseArr int[sum+1][3]
3.将二维数组的有效数据存入稀疏数组。
稀疏数组转二维数组的思路
1.读取稀疏数组中的总行数、总列数
2.根据总行数、总列数创建相应大小的二维数组
3.将稀疏数组中存储的有效值按稀疏数组记录的行、列还原到二维数组中
代码实现
二维数组转稀疏数组
//创建二维数组
int[][] arr = new int[8][8];
arr[3][5] = 1;
arr[7][1] = 8;
arr[6][4] = 4;
//遍历数组,打印出原始二维数组的效果并记录有效值的个数
int sum = 0;
for (int[] ints : arr) {
for (int anInt : ints) {
System.out.print(anInt+" ");
if(anInt != 0){
sum++;
}
}
System.out.println();
}
//创建稀疏数组,行数为有效值个数+1,列数为3
int[][] sArr = new int[sum+1][3];
sArr[0][0] = arr.length; //记录原始二维数组的行数
sArr[0][1] = arr[0].length; //记录原始二维数组的列数
sArr[0][2] = sum; //记录原始二维数组中的有效值个数
//记录本次向稀疏数组中添加的是第几个有效值
int count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++){
if(arr[i][j] != 0){
count++;
sArr[count][0] = i;
sArr[count][1] = j;
sArr[count][2] = arr[i][j];
}
}
}
//打印稀疏数组
for (int[] ints : sArr) {
for (int anInt : ints) {
System.out.print(anInt+" ");
}
System.out.println();
}
//将稀疏数组存储在硬盘上
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("sparseness_array.date");
oos = new ObjectOutputStream(fos);
oos.writeObject(sArr);
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
稀疏数组转二维数组
//从磁盘中读取存储的稀疏数组
FileInputStream fis = null;
ObjectInputStream ois = null;
Object obj = null;
try {
fis = new FileInputStream("sparseness_array.date");
ois = new ObjectInputStream(fis);
obj = ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//将读取的obj对象转换为二维数组对象
int[][] readSArr = (int[][]) obj;
//从稀疏数组中读取原始二维数组的行、列数
int row = readSArr[0][0];
int col = readSArr[0][1];
//创建原始二维数组
int[][] rArr = new int[row][col];
//将稀疏数组中记录的值添加到原始二维数组中
for (int i = 1; i < readSArr.length; i++){
row = readSArr[i][0];
col = readSArr[i][1];
rArr[row][col] = readSArr[i][2];
}
//打印恢复的原始二维数组
for (int[] ints : rArr) {
for (int anInt : ints) {
System.out.print(anInt+" ");
}
System.out.println();
}