标签:图片 i++ ret ash public pre bsp com ima
如果数组中分布有大量的元素 0,即非 0 元素非常少,这类数组称为稀疏数组。
压缩存储稀疏数组的方法是:只存储数组中的非 0 元素,与前面的存储方法不同数组,矩阵非 0 元素的存储需同时存储该元素所在数组
/** * 数组转稀疏数组 */ public static int[][] Test1(int[][] nums) { int count = 0;//计数器 int row = 0;//行 int col = 0;//列 for (int i = 0; i < nums.length; i++) { int[] items = nums[i]; col = items.length; for (int j = 0; j < items.length; j++) { if (nums[i][j] != 0) { count++; row = nums.length; } } } int[][] zipArr = new int[row + 1][3]; zipArr[0][0] = row; zipArr[0][1] = col; zipArr[0][2] = count; count = 0; for (int i = 0; i < nums.length; i++) { int[] items = nums[i]; col = items.length; for (int j = 0; j < items.length; j++) { if (nums[i][j] != 0) { count++; zipArr[count][0] = i; zipArr[count][1] = j; zipArr[count][2] = nums[i][j]; } } } return zipArr; } /** * 稀疏数组转数组 */ public static int[][] Test2(int[][] item) { int[][] ars = new int[item[0][0]][item[0][1]]; for (int i = 1; i < ars.length+1; i++) { ars[item[i][0]][item[i][1]]=item[i][2]; } return ars; }
输出
3 3 3 0 0 1 1 2 5 2 0 3 1 0 0 0 0 5 3 0 0
标签:图片 i++ ret ash public pre bsp com ima
原文地址:https://www.cnblogs.com/lIllIll/p/11376657.html