Java編程內功-數據結構與算法「稀疏數組」
作者:Java精髓
當一個數組中大部分元素為0,或者為同一個值的數組時,可以使用稀疏數組來保存該數組,本篇就給大家介紹關于稀疏數組的相關知識。
基本介紹
當一個數組中大部分元素為0,或者為同一個值的數組時,可以使用稀疏數組來保存該數組.
稀疏數組的處理方法是:
- 記錄數組一共有幾行幾列,有多少個不同的值.
- 把具有不同值的元素的行列記錄在一個小規模的數組中,從而縮小程序的規模.
舉例說明
原始的二維數組

原始的二維數組
轉換后的二維數組
第一行記錄原始數組有多少行列,多少值(8<<代表原始數組的值的個數22,15,11,17,-6,39,91,28>>)

轉換后的二維數組
二維數組轉稀疏數組思路
- 遍歷原始的二維數組,得到有效數據的個數sum
- 根據sum就可以創建稀疏數組sparseArr int(sum+1)(3)
- 將二維數組的有效數據存入到稀疏數組
稀疏數組轉原始二維數組思路
- 先讀取稀疏數組的第一行,根據第一行的數據,創建原始的二維數組
- 再讀取稀疏數組后幾行的數據,并賦給原始的二維數組即可.
應用實例
- 使用稀疏數組,來保留類似前面的二維數組(棋盤\地圖)等
- 把稀疏數組存盤,并且可重新恢復原來的二維數組數
代碼案例
- package com.structures.sparsearray;
- public class SparseArray {
- public static void main(String[] args) {
- //創建一個原始的二維數組11*11
- //0:表示沒有棋子,1表示黑子,2表示白子
- int[][] chessArr1 = new int[11][11];
- chessArr1[1][2] = 1;
- chessArr1[2][3] = 2;
- //輸出原始二維數組
- System.out.println("原始的二維數組");
- for (int[] ints : chessArr1) {
- for (int anInt : ints) {
- System.out.printf("%d\t", anInt);
- }
- System.out.println();
- }
- //將二維數組轉稀疏數組
- //1.先遍歷二維數組,得到非0數據的個數.
- int sum = 0;
- for (int[] ints : chessArr1) {
- for (int anInt : ints) {
- if (anInt != 0) {
- sum++;
- }
- }
- }
- System.out.println("sum = " + sum);
- //2.創建對應的稀疏數組
- int[][] sparseArr = new int[sum + 1][3];
- //給稀疏數組賦值
- sparseArr[0][0] = 11;
- sparseArr[0][1] = 11;
- sparseArr[0][2] = sum;
- //遍歷原始數組,將非0的值存放到稀疏數組中
- int count = 0;//count用于記錄第幾個非0數據
- for (int i = 0; i < chessArr1.length; i++) {
- for (int j = 0; j < chessArr1[i].length; j++) {
- if (chessArr1[i][j] != 0) {
- count++;
- sparseArr[count][0] = i;
- sparseArr[count][1] = j;
- sparseArr[count][2] = chessArr1[i][j];
- }
- }
- }
- //輸出稀疏數組
- System.out.println();
- System.out.println("得到的稀疏數組為~~~~");
- for (int[] ints : sparseArr) {
- for (int anInt : ints) {
- if (anInt != 0) {
- System.out.printf("%d\t", anInt);
- }
- }
- System.out.println();
- }
- //將稀疏數組恢復成原始數組
- int[][] chessArr2 = new int[sparseArr[0][0]][sparseArr[0][1]];
- for (int i = 0; i < sparseArr[0][2]; i++) {
- chessArr2[sparseArr[i + 1][0]][sparseArr[i + 1][1]] = sparseArr[i + 1][2];
- }
- //恢復后的原始數組
- System.out.println("恢復后的原始數組");
- for (int[] ints : chessArr2) {
- for (int anInt : ints) {
- System.out.printf("%d\t", anInt);
- }
- System.out.println();
- }
- }
- }
- /*
- 原始的二維數組
- 0 0 0 0 0 0 0 0 0 0 0
- 0 0 1 0 0 0 0 0 0 0 0
- 0 0 0 2 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0
- sum = 2
- 得到的稀疏數組為~~~~
- 11 11 2
- 1 2 1
- 2 3 2
- 恢復后的原始數組
- 0 0 0 0 0 0 0 0 0 0 0
- 0 0 1 0 0 0 0 0 0 0 0
- 0 0 0 2 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0
- */
【編輯推薦】
責任編輯:姜華
來源:
今日頭條