其他分享
首页 > 其他分享> > 稀疏数组

稀疏数组

作者:互联网

 1 public class demo04 {
 2     public static void main(String[] args) {
 3         //定义原始数组
 4         int[][] array1 = new int[11][11];
 5         array1[1][2] = 1;
 6         array1[2][3] = 1;
 7         //输出原始数组
 8         System.out.println("====原始数组====");
 9         for (int i = 0; i < array1.length; i++) {
10             for (int j = 0; j < array1[i].length; j++) {
11                 int a = array1[i][j];
12                 System.out.print(a);
13             }
14             System.out.println();
15         }
16         //获取有效值的个数
17         int sum = 0;
18         for (int i = 0; i < 11; i++) {
19             for (int j = 0; j < 11; j++) {
20                 if (array1[i][j] != 0) {
21                     sum++;
22                 }
23             }
24         }
25         System.out.println("有效值个数为" + sum);
26 
27         // 创建稀疏数组
28         int[][] array2 = new int[sum + 1][3];
29         array2[0][0] = 11;
30         array2[0][1] = 11;
31         array2[0][2] = sum;
32         int he = 0;
33         //遍历二维数组,将有效值录入稀疏数组中
34         for (int i = 0; i < array1.length; i++) {
35             for (int j = 0; j < array1[i].length; j++) {
36                 if (array1[i][j] != 0) {
37                     he++;
38                     array2[he][0] = i;
39                     array2[he][1] = j;
40                     array2[he][2] = array1[i][j];
41                 }
42             }
43         }
44         System.out.println("====稀疏数组====");
45         for (int i = 0; i < he; i++) {
46             System.out.println(array2[i][0] + "\t" + array2[i][1] + "\t" + array2[i][2] + "\t");
47         }
48         ;
49         //数组还原
50         System.out.println("====数组还原====");
51         //读取稀疏数组
52         int[][] array3 = new int[array2[0][0]][array2[0][1]];
53         //录入有效值
54         for (int i = 1; i < array2.length; i++) {
55             array3[array2[i][0]][array2[i][1]]=array2[i][2];
56         }
57         for (int i = 0; i < array3.length; i++) {
58             for (int j = 0; j < array3[i].length; j++) {
59                 int a = array1[i][j];
60                 System.out.print(a);
61             }
62             System.out.println();
63         }
64     }

65 }

 

 

 

标签:int,array2,array1,稀疏,System,++,数组,out
来源: https://www.cnblogs.com/guojianglong/p/16499395.html