2021/9/13 稀疏数组
数组与稀疏数组转换
二维数组转稀疏数组
- 遍历原始的二维数组,得到有效数据的个数sum
- 根据sum就可以创建稀疏数组sparse int[sum] [3]
- 将二维数组的有效数据存到稀疏数组
稀疏数组转二维数组
- 先读取稀疏数组的第一行数据,得到行列的信息,创建 chessArr = int[11] [11]
- 再读取稀疏数组后 几行
package sparseArray;
public class sparseArrayDemo01 {
public static void main(String[] args) {
int chessArray[][] = new int[11][11];
chessArray[1][2] = 1;
chessArray[2][3] = 2;
for (int[] row : chessArray){
for (int data:row){
System.out.printf("%5d ",data);
}
System.out.println();
}
int sum = 0;
// 遍历
for (int[] row : chessArray){
for (int data:row){
if (data!=0) sum++;
}
}
System.out.println("==================");
int sparse[][] = new int[sum+1][3];
sparse[0][0] = 11;
sparse[0][1] = 11;
sparse[0][2] = sum;
int count = 1;
for (int i = 0; i < 11; i++) {
for (int j = 0; j <11 ; j++) {
if (chessArray[i][j]!=0){
sparse[count][0] = i;
sparse[count][1] = j;
sparse[count][2] = chessArray[i][j];
count++;
}
}
}
for (int[] row : sparse){
for (int data:row){
System.out.printf("%5d ",data);
}
System.out.println();
}
System.out.println("数组===转换==》稀疏数组开始了");
int chessArrays[][] = new int[sparse[0][0]][sparse[0][1]];
int sums = sparse[0][2];
for (int i = 1; i <= sums; i++) {
chessArrays[sparse[i][0]][sparse[i][1]] = sparse[i][2];
}
for (int[] row : chessArrays){
for (int data:row){
System.out.printf("%5d ",data);
}
System.out.println();
}
}
}
循环队列:
https://blog.csdn.net/weixin_44187730/article/details/96141225
链表更深记忆: