简介
稀疏数组是为了减少大型数组中的无效数据对计算机存储空间的浪费。
普通数组:
0 0 0 0 0 0 0
1 0 0 0 0 0 0
0 0 0 0 2 0 0
0 0 0 0 0 0 0
3 0 0 0 0 0 0
对于这么一个五行七列的数组,其中大部分都是无效数据0,完整存储将造成存储空间的巨大浪费。
因此完全可以另外创建一个数组,使其只保存数组中的有效数据。这个数组一般是一个n行3列的数组。
例如上面数组压缩过后的三元数组为:
5 7 3 //第一行数据保存的是,行数,列数,有效数据数(非0的数量)
1 0 1 //第二行保存的是第一个有效数据在数组中的位置以及自身的值
2 4 2 //第三行保存的是第二个有效数据在数组中的位置以及自身的值
4 0 3 // 依次类推。。。第n行保存的是第n个有效数据在数组中的位置以及自身的值
public class SparseArray {
public int[][] createSparseArray(){
int[][] sparseArray = new int[6][7];
sparseArray[1][5] = 1;
sparseArray[3][2] = 2;
System.out.println("------------原稀疏数组------------");
for (int[] ints : sparseArray) {
for (int anInt : ints) {
System.out.printf("%d\t",anInt);
}
System.out.println();
}
System.out.println("------------------------------");
return sparseArray;
}
public int[][] transferToThreeArray(int[][] sparseArray) throws IOException {
int rowLen = sparseArray.length;
int colLen = sparseArray[0].length;
int valueCount = 0;
for (int[] ints : sparseArray) {
for (int anInt : ints) {
if (anInt != 0){
valueCount ++;
}
}
}
int[][] threeArray = new int[valueCount+1][3];
threeArray[0][0] = rowLen;
threeArray[0][1] = colLen;
threeArray[0][2] = valueCount;
int tempLen = 0;
for (int i = 0; i < sparseArray.length; i++) {
for (int i1 = 0; i1 < sparseArray[i].length; i1++) {
if (sparseArray[i][i1] != 0){
++tempLen;
threeArray[tempLen][0] = i;
threeArray[tempLen][1] = i1;
threeArray[tempLen][2] = sparseArray[i][i1];
}
}
}
System.out.println("------------三元数组------------");
for (int[] ints : threeArray) {
for (int anInt : ints) {
System.out.printf("%d\t",anInt);
}
System.out.println();
}
System.out.println("------------------------------");
File file = new File("./threeArray.txt");
FileOutputStream fileOutputStream = new FileOutputStream(file);
FileChannel channel = fileOutputStream.getChannel();
byte[] bytes = JSONObject.toJSONBytes(threeArray);
channel.write(ByteBuffer.wrap(bytes));
return threeArray;
}
public int[][] transferToSparseArray(int[][] threeArray){
int rowLen = threeArray[0][0];
int colLen = threeArray[0][1];
int[][] sparseArray = new int[rowLen][colLen];
for (int i = 1; i < threeArray.length; i++) {
sparseArray[threeArray[i][0]][threeArray[i][1]] = threeArray[i][2];
}
System.out.println("------------还原后的稀疏数组------------");
for (int[] ints : sparseArray) {
for (int anInt : ints) {
System.out.printf("%d\t",anInt);
}
System.out.println();
}
System.out.println("------------------------------");
return null;
}
public static void main(String[] args) throws IOException {
int[][] sparseArray = new SparseArray().createSparseArray();
int[][] threeArray = new SparseArray().transferToThreeArray(sparseArray);
new SparseArray().transferToSparseArray(threeArray);
}
}