数据结构与算法(一)稀疏数组
应用场景
放一个数据中大部分元素是0,或者同一个值的数组时,可以使用稀疏数组来保存该数组
处理方式
- 记录数组一共有几行几列,有多少不同的值
2.把具有不同值的元素的行列以即值记录在小规模的数组中。
例子
代码
public class SparseArray {
public static void main(String[] args) {
int[][] chessArrayOld = new int[6][7];
chessArrayOld[0][3] = 22;
chessArrayOld[0][6] = 15;
chessArrayOld[1][1] = 11;
chessArrayOld[1][5] = 17;
chessArrayOld[2][3] = -6;
chessArrayOld[3][5] = 39;
chessArrayOld[4][0] = 91;
chessArrayOld[5][2] = 28;
System.out.println("Original Array-----------------------------------");
for (int i = 0; i < chessArrayOld.length; i++) {
for(int j = 0; j< chessArrayOld[0].length; j++){
System.out.printf("%d\t", chessArrayOld[i][j]);
}
System.out.println();
}
int[][] sparseArray = chessToSparse(chessArrayOld);
System.out.println("Sparse Array-----------------------------------");
for (int i = 0; i < sparseArray.length; i++) {
for(int j = 0; j< sparseArray[0].length; j++){
System.out.printf("%d\t", sparseArray[i][j]);
}
System.out.println();
}
int[][] chessArrayNew = sparseToChess(sparseArray);
System.out.println("New Array-----------------------------------");
for (int i = 0; i < chessArrayNew.length; i++) {
for(int j = 0; j< chessArrayNew[0].length; j++){
System.out.printf("%d\t", chessArrayNew[i][j]);
}
System.out.println();
}
}
private static int[][] sparseToChess(int[][] sparseArray) {
int[][] chessArray = new int[sparseArray[0][0]][sparseArray[0][1]];
int sum = sparseArray[0][2];
for (int i = 1; i < sum + 1; i++) {
chessArray[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
}
return chessArray;
}
private static int[][] chessToSparse(int[][] chessArrayOld) {
//get the total number of non-zero
int sum = 0;
for (int i = 0; i < chessArrayOld.length; i++) {
for (int j = 0; j < chessArrayOld[0].length; j++) {
if (chessArrayOld[i][j] != 0){
sum++;
}
}
}
int[][] sparseArray = new int[sum+1][3];
sparseArray[0][0] = chessArrayOld.length;
sparseArray[0][1] = chessArrayOld[0].length;
sparseArray[0][2] = sum;
int count = 0;
for (int i = 0; i < chessArrayOld.length; i++) {
for (int j = 0; j < chessArrayOld[0].length; j++) {
if (chessArrayOld[i][j] != 0){
count = count + 1;
sparseArray[count][0] = i;
sparseArray[count][1] = j;
sparseArray[count][2] = chessArrayOld[i][j];
}
}
}
return sparseArray;
}
}