用途:将普通数组转为稀疏数组来达到节省空间的目的
介绍:
代码:
import cn.hutool.core.util.ObjectUtil; import org.junit.Test; public class SparseArrayTest { @Test public void test() { Integer[][] integers = new Integer[6][7]; integers[0][3] = 22; integers[0][6] = 15; integers[1][1] = 11; integers[1][5] = 17; integers[2][3] = -6; integers[3][5] = 39; integers[4][0] = 91; integers[5][2] = 28; System.out.println("~~~原始数组~~~"); SparseArray.showArray(integers); Integer[][] sparseArray = SparseArray.toSparseArray(integers); System.out.println("~~~稀疏数组~~~"); SparseArray.showArray(sparseArray); Integer[][] ordinaryArray = SparseArray.toOrdinaryArray(sparseArray); System.out.println("~~~普通数组~~~"); SparseArray.showArray(ordinaryArray); } } class SparseArray { /** * 普通数组转为稀疏数组 * @param source * @return */ public static Integer[][] toSparseArray(Integer[][] source) { //对source的有效数据进行计数 int count = 0; for (int i = 0; i < source.length; i++) { for (int j = 0; j < source[i].length ; j++) { if (ObjectUtil.isNotNull(source[i][j])) { count++; } } } //创建稀疏数组 Integer[][] sparseArray = new Integer[count + 1][3]; //设置稀疏数组第一行的数据 sparseArray[0][0] = source.length; sparseArray[0][1] = source[0].length; sparseArray[0][2] = count; //将有效数据放进稀疏数组 count = 0; for (int i = 0; i < source.length; i++) { for (int j = 0; j < source[i].length ; j++) { if (ObjectUtil.isNotNull(source[i][j])) { count ++; sparseArray[count][0] = i; sparseArray[count][1] = j; sparseArray[count][2] = source[i][j]; } } } return sparseArray; } /** * 稀疏数组转为普通数组 * @param source * @return */ public static Integer[][] toOrdinaryArray(Integer[][] source) { //新建普通数组 Integer[][] ordinaryArray = new Integer[source[0][0]][source[0][1]]; for (int i = 1; i < source.length; i++) { ordinaryArray[source[i][0]][source[i][1]] = source[i][2]; } return ordinaryArray; } /** * 在控制台打印数组 * @param source */ public static void showArray(Integer[][] source) { for (int i = 0; i < source.length; i++) { for (int j = 0; j < source[i].length; j++) { if (ObjectUtil.isNull(source[i][j])) { System.out.printf("00\t"); continue; } System.out.printf("%d\t", source[i][j]); } System.out.println(); } } }
标签:count,integers,sparseArray,稀疏,source,数组,Integer From: https://www.cnblogs.com/xueseng/p/17030166.html