稀疏数组
一.定义
稀疏数组是用于存储多维数组有效数据的一种结构,如果多维数组中有很多没有意义的数据,
就可以使用稀疏数组来存储,可以达到有效的节省内存空间的目的.
二.分析
首先定义一个二维数组,存储2个有效数据
public static void main(String[] args) {
//模拟棋盘的二维数组
int [][] chess = new int[11][10];
chess[1][2] = -2;
chess[2][3] = 15;
for (int [] c:chess
) {
for (int d:c
) {
System.out.printf("%d\t",d);
}
System.out.println("\n");
}
}
看一下输出
可以看到有效数据只有两个,大多是无效数据,这时就可以使用稀疏数组存储了
如果使用稀疏数组应该怎么存储呢?
1)记录一共有几行几列,有多少个有效值(第一行)
2)把值的元素的行列记录在稀疏数组中,从而缩小程序的规模(第二行开始)
稀疏数组存储后数据结构变化以及对比(下图中行和列都是从0开始计算)
以上可以看出,稀疏数组 列 是固定的3列,行为有效数字+1行 **+1是因为第一行固定存储数据为多维数组中的 行数 列数 以及有效值数量,从第二行开始存储的是有效数据所在行数 列数 以及有效数据具体值。**对比发现,稀疏数组所占用内存更少
三.多维数组与稀疏数组相互转换代码实现
public class demo1 {
public static void main(String[] args) {
int [][] xs = new int[10][5];
xs[0][4] = 1;
xs[1][4] = 10;
int[][] ttx = ttx(xs);
int[][] xtt = xtt(ttx);
for (int [] c:xtt
) {
for (int s:c
) {
System.out.print(s+" ");
}
System.out.println("\n");
}
}
/**
* 二维数组转稀疏数组
* */
public static int[][] ttx(int [][] er){
//行
int h = 0;
//列
int l = 0;
//有效数
int num = 0;
//生成二维数组的记录行
int count = 0;
for (int [] k: er
) {
for (int c: k
) {
if(c!=0){
num+=1;
}
l+=1;
}
h+=1;
}
int [][] res = new int[num+1][3];
res[0][0] = l/h;
res[0][1] = h;
res[0][2] = num;
for (int i = 0; i < er.length; i++) {
for (int j = 0; j < er[i].length; j++) {
if(er[i][j]!=0){
count+=1;
res[count][0] = i;
res[count][1] = j;
res[count][2] = er[i][j];
}
}
}
return res;
}
/**
* 稀疏数组转二维数组
* */
public static int[][] xtt(int [] [] xs){
int [][] res = new int[xs[0][1]][xs[0][0]];
for (int i = 1; i < xs.length; i++) {
for (int j = 0; j < xs[i].length; j++) {
res[xs[i][0]][xs[i][1]] = xs[j][2];
}
}
return res;
}
}