Java数据结构-稀疏数组
基本介绍
当一个数组中大部分元素为0,或者为同一个值的数组时,可以使用稀疏数组来保存该数组。
稀疏数组的处理方法是:
记录数组一共有几行几列,有多少个不同的值
把具有不同值的元素的行列及值记录在一个小规模的数组中,从而缩小程序的规模
先看一个实际需求
可以将上述的6*7的二维数组压缩为9*3的稀疏数组。
1.二维数组转稀疏数组
思路:
1.遍历原始二维数组,得到非0的有效数组个数sum。
2.根据sum就可以创建稀疏数组sparseArray[sum+1][3] (对于稀疏数组,行为sum+1,列为3)
3.将二维数组的有效数组存入到稀疏数组
package com.itcy.sparsearray;
public class SparseArray {
public static void main(String[] args) {
//创建原始数组
int[][] chessArray = new int[11][11];
chessArray[1][2] = 1;
chessArray[2][3] = 2;
//遍历数组并记录数组中非0值的个数
int sum = 0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (chessArray[i][j] != 0) {
sum++;
}
}
}
System.out.println(sum);
//定义稀疏数组,稀疏数组的行为sum+1,列固定为3
int[][] sparseArray = new int[sum + 1][3];
//为稀疏数组第一行赋值
sparseArray[0][0] = 11;
sparseArray[0][1] = 11;
sparseArray[0][2] = sum;
//取出里面每个有效值赋给稀疏数组
int count = 0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (chessArray[i][j] != 0) {
count++;
sparseArray[count][0] = i;
sparseArray[count][1] = j;
sparseArray[count][2] = chessArray[i][j];
}
}
}
//输出稀疏数组
System.out.println("得到的稀疏数组为:");
for (int i = 0; i < sparseArray.length; i++) {
System.out.printf("%d\t%d\t%d\t\n", sparseArray[i][0], sparseArray[i][1], sparseArray[i][2]);
}
}
结果:
2.稀疏数组转二维数组
思路:
1.先读取稀疏数组第一行,根据第一行的数据创建二维数组
(二维数组的行为稀疏数组的 [0][0],列为 [0][1])
2.遍历稀疏数组,赋值给二维数组
//将稀疏数组转换为原始二维数组
int[][] chessArray2 = new int[sparseArray[0][0]][sparseArray[0][1]];
for (int i = 1; i < sparseArray.length; i++) {
chessArray2[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
}
//
System.out.println("恢复的二维数组");
for (int[] row : chessArray2) {
for (int item : row) {
System.out.print(item);
}
}
}
结果:
3.将稀疏数组写入磁盘并读出
static File file = new File("E:\\java\\DateStructures\\src\\com\\itcy\\SparseArray.data");
//稀疏数组写入磁盘
public static void saveToFile(int[][] sparseArray) throws IOException {
FileWriter fileWriter = new FileWriter(file);
for(int[] array : sparseArray){
fileWriter.write(array[0]+"\t"+array[1]+"\t"+array[2]);
fileWriter.write("\r\n");
}
fileWriter.close();
// new FileWriter()
}
// 从磁盘中读取稀疏数组
public static int[][] readFromFile() throws Exception {
int[][] sparseArray=null;
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line=null;
boolean isFirstLine= true;
int row=0; //读取到第几行
while ((line = bufferedReader.readLine()) != null){
String[] sparseRow = line.split("\t");
if(isFirstLine){
// 读到的是字符串 需要转为int
sparseArray = new int[Integer.parseInt(sparseRow[2])+1][3];
sparseArray[row][0] = Integer.parseInt(sparseRow[0]);
sparseArray[row][1] = Integer.parseInt(sparseRow[1]);
sparseArray[row][2] = Integer.parseInt(sparseRow[2]);
isFirstLine= false;
}else{
sparseArray[row][0] = Integer.parseInt(sparseRow[0]);
sparseArray[row][1] = Integer.parseInt(sparseRow[1]);
sparseArray[row][2] = Integer.parseInt(sparseRow[2]);
}
row++;
}
return sparseArray;
}
谢谢大家的阅读
若有误,请指教!