Java data structure and algorithm: sparse array (SparseArray)

Compilation software: IntelliJ IDEA 2019.2.4 x64
Operating system: win10 x64-bit Home Edition



insert image description here


1. What is a sparse array?

1.1 Basic introduction

When most elements in an array are 0, or an array of the same value, you can use a sparse array to save the array.

1.2 Processing method of sparse array

  1. How many rows and columns are there in the record array, and how many different values ​​are there?
  2. Record the rows, columns and values ​​of elements with different values ​​in a small-scale array, thereby reducing the size of the program

1.3 Examples

insert image description here


2. Why use sparse arrays?

2.1 First look at this specific application requirement

question

In the written backgammon program, there are functions of saving, exiting and reloading, as shown in the figure below

insert image description here

In the above-mentioned 11X11 backgammon board, if it is necessary to perform the functions of saving, exiting and reloading, it is necessary to download the current chessboard state information to the local or upload the last stored chessboard state information to the program. Then at this time, a data structure is needed to store the chessboard state information of the battle.

The usual practice is to use a native two-dimensional array to record the state information of the chessboard, but this will expose a problem:二维数组的很多值如果不赋值,那么会被程序主动赋默认值,比如int类数组会被赋值为0,因此二维数组中会记录了很多没有意义的数据,造成内存空间的极大浪费。

solution

At this time, we can consider using a sparse array to "compress" all the data in the original two-dimensional array, thereby improving the space utilization of the original two-dimensional array

2.2 Advantages and disadvantages of using sparse arrays

advantage

  • 提高空间利用率: Sparse arrays only store element information with non-default values, which can greatly reduce the storage space occupied
  • 方便进行压缩和解压缩: Sparse arrays can be easily compressed and decompressed, very useful for the storage and transmission of large sparse matrices
  • 提高运算效率: When performing operations on sparse arrays, only non-default value elements can be processed to avoid invalid operations on all elements, thereby improving operation efficiency.

shortcoming

  • 降低数组的访问速度: Since the location information of non-default value elements in sparse arrays requires additional storage, accessing these elements is relatively slow, especially in large-scale sparse matrices.
  • 需要进行额外的处理: The use of sparse arrays requires additional processing of element position information, which increases code complexity and maintenance costs.

To sum up, sparse arrays are suitable for situations where most of the elements are default values ​​or repeated values , which can significantly reduce the storage space occupied; but at the same time, special attention should be paid to its access speed and code complexity .


3. How to use sparse arrays?

3.1 Application examples

  1. Use sparse arrays to keep similar to the previous two-dimensional array (chessboard, map, etc.)

  2. Save the sparse array to disk, and restore the original two-dimensional array data

  3. Overall thinking analysis
    '
    insert image description here
    ① The thinking of converting two-dimensional array to sparse array

    1.遍历原始的二维数组,得到有效数据的个数sum

    2.根据sum就可以创建稀疏数组sparseArr int[sum+1)][3]

    3.将二维数组的有效数据数据存入到稀疏数组

    ②The idea of ​​converting sparse arrays to original two-dimensional arrays

    1.先读取稀疏数组的第一行,根据第一行的数据,创建原始的二维数组,比如上面的chessArr2=int[11][11]

    2.在读取稀疏数组后几行的数据,并赋给原始的二维数组即可.

3.2 The application code is as follows

//稀疏键盘
public class t2 {
    
    

    public static void main(String[] args) {
    
    
        //定义原始棋盘的落子情况【二维数组】
        int[][] arr=new int[11][11];
        //1 -> 黑子,2 -> 篮子,0 -> 无子
        arr[1][2]=1;
        arr[2][3]=2;
        arr[5][2]=3;
        int sum=0;
        System.out.println("二维数组:" );
        for (int[] ints : arr) {
    
    
            for (int data : ints) {
    
    
                if (data!=0){
    
    
                    sum++;
                }
                System.out.print(data+"\t");
            }
            System.out.println();
        }

        //二维数组转为稀疏数组
        int[][] sparseArr=new int[sum+1][3];
        sparseArr[0][0]=11;
        sparseArr[0][1]=11;
        sparseArr[0][2]=sum;
        int count=0;
        for (int i = 0; i < arr.length ; i++) {
    
    
            for (int j = 0; j < arr[i].length; j++) {
    
    
                if (arr[i][j]!=0){
    
    
                    count++;
                    sparseArr[count][0]=i;
                    sparseArr[count][1]=j;
                    sparseArr[count][2]=arr[i][j];
                }
            }
        }

        System.out.println("稀疏数组:");
        for (int[] ints : sparseArr) {
    
    
            for (int data : ints) {
    
    
                System.out.print(data+"\t");
            }
            System.out.println();
        }

        //将稀疏数组恢复为二维数组newArr
        //1。先读取稀硫数组的第一行,根据第一行的数据,创建原始的二维数组
        int[][] newArr=new int[sparseArr[0][0]][sparseArr[0][1]];
		
		//2.在读取稀疏数组后几行的数据,并赋给原始的二维数组即可
        for (int i = 1; i < sparseArr.length ; i++) {
    
    
            for (int j = 0; j < sparseArr[i].length ; j++) {
    
    
                if (j>1){
    
    
                    int row=sparseArr[i][j-2];
                    int col=sparseArr[i][j-1];
                    newArr[row][col]=sparseArr[i][j];
                }
            }
        }

        //打印恢复后的二维数组newArr
        System.out.println("打印新二维数组newArr:");
        for (int[] ints : newArr) {
    
    
            for (int data : ints) {
    
    
                System.out.print(data+"\t");
            }
            System.out.println();
        }

    }
}

insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/siaok/article/details/131733364