稀疏数组sparseArray详解
1.背景
2.代码
package com.ldp.structure.demo01SparseArray; import org.junit.Test; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * @author 姿势帝-博客园 * @address https://www.cnblogs.com/newAndHui/ * @WeChat 851298348 * @create 04/09 8:25 * @description* 博客:
https://www.cnblogs.com/butingxue/p/16120794.html * */ public class Test01 { @Test public void test01() { int[][] array = createArray(); printArray(array, "二维数组"); int[][] sparseArray = arrayToSparse(array); printArray(sparseArray, "稀疏数组"); int[][] arrayNew = sparseToArray(sparseArray); printArray(arrayNew, "稀疏数组-->二维数组"); } /** * 1.确定稀疏数组的行:遍历数组得到数组的值个数n,n+1作为稀疏数组的行 * 2.稀疏数组的列为固定值3 * 二维数组转为稀疏数组 */ public int[][] arrayToSparse(int[][] array) { // 确定数组有效值个数 int row = 0, col = 0, n = 0; // 记录二维数组每个值的行列值,格式(行,列,值) LinkedListarrayStrList = new LinkedList<>(); for (int[] ints : array) { row++; col = 0; for (int anInt : ints) { col++; if (anInt != 0) { n++; // 行,列,值 String str = "" + (row - 1) + "," + (col - 1) + "," + anInt; arrayStrList.addLast(str); } } } // 第一行是 行,列,个数 String strFirst = "" + row + "," + col + "," + n; arrayStrList.addFirst(strFirst); // 创建稀疏数组对象 int[][] sparseArray = new int[n + 1][3]; for (int i = 0; i < (n + 1); i++) { String s = arrayStrList.get(i); // System.out.println(s); String[] rowStr = s.split(","); sparseArray[i][0] = Integer.valueOf(rowStr[0]); sparseArray[i][1] = Integer.valueOf(rowStr[1]); sparseArray[i][2] = Integer.valueOf(rowStr[2]); } return sparseArray; } /** * 稀疏数组转二维数组 * * @param sparseArray * @return */ public int[][] sparseToArray(int[][] sparseArray) { int row = sparseArray[0][0]; int col = sparseArray[0][1]; int n = sparseArray[0][2]; int[][] array = new int[row][col]; for (int i = 1; i < n; i++) { int row_ = sparseArray[i][0]; int col_ = sparseArray[i][1]; int value_ = sparseArray[i][2]; array[row_][col_] = value_; } return array; } /** * 创建五子棋盘 */ public int[][] createArray() { int[][] array = new int[11][11]; array[1][2] = 1; array[2][3] = 2; array[2][4] = 1; array[4][6] = 2; return array; } /** * 打印数组 * * @param array */ public void printArray(int[][] array, String message) { System.out.println("----------" + message + "-----start-----------"); for (int[] ints : array) { for (int anInt : ints) { System.out.printf("%d\t", anInt); } System.out.println(); } System.out.println("----------" + message + "------end------------"); } }
测试结果