Java方法之稀疏数组
2024-10-21 11:47:38
稀松数组
- 当一个数组中大部分元素为0,或者为同一值的数组时,可以使用稀疏数组来保存该数组。
- 稀疏数组的处理方式是:
1、记录数组一共有几行几列,有多少个不同值
2、把具有不同值的元素和行列及值记录在一个小规模的数组中,从而缩小程序的规模
3、如下图:左边是原始数组,右边是稀疏数组
public class ArraysDemo07 {
public static void main(String[] args) {
//1.创建一个二维数组 11*11 0:没有棋子 1:黑棋 2:白棋
int[][] array1 = new int[11][11];
array1[1][2] = 1;
array1[2][3] = 2;
//输出原始的数组
System.out.println("输出原始的数组:");
for (int[] ints : array1) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}
System.out.println("================");
//转换为稀疏数组保存
//获取有效值的个数
int sum = 0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (array1[i][j]!=0){
sum++;
}
}
}
System.out.println("有效值的个数:"+sum);
//2.创建一个稀疏数组的数组
int[][] array2 = new int[sum+1][3];
array2[0][0] = 11;
array2[0][1] = 11;
array2[0][2] = sum;
//遍历二维数组,将非零的值,存放到稀疏数组中
int count = 0;
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array1[i].length; j++) {
if (array1[i][j] != 0){
count++;
array2[count][0] = i;
array2[count][1] = j;
array2[count][2] = array1[i][j];
}
}
}
//输出稀疏数组
System.out.println("稀疏数组");
for (int i = 0; i < array2.length; i++) {
System.out.println(array2[i][0]+"\t"
+array2[i][1]+"\t"
+array2[i][2]+"\t");
}
System.out.println("================");
System.out.println("还原稀疏数组");
//1.读取稀疏数组
int[][] array3 = new int[array2[0][0]][array2[0][1]];
//2.给其中的元素还原它的值
for (int i = 1; i < array2.length; i++) {
array3[array2[i][0]][array2[i][1]] = array2[i][2];
}
//3.打印
System.out.println("输出还原的数组:");
for (int[] ints : array3) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}
}
}
"哦,你也在这里吗?"——作家,张爱玲,《流言》
最新文章
- WdatePicker 没有权限 不能执行已释放 Script 的代码
- 关于IOS的证书、App ID、设备、Provisioning Profile详述
- hdu 1052 (greedy algorithm) 分类: hdoj 2015-06-18 16:49 35人阅读 评论(0) 收藏
- jQueryMobile控件之复选框
- linux环境变量查看及修改
- Rsync企业实战之自动异地备份(转)
- Kinect For Windows V2开发日志三:简单的深度读取
- 国内外开源与 SaaS ,团队协作平台、项目管理工具整理
- try与finally返回结果执行先后详解
- C++函数二义性问题,我怎么感觉编译器有偷懒嫌疑!!!
- iOS 10 个实用小技巧(总有你不知道的和你会用到的)
- Android 异步链式调用设计
- 用JAVA代码获取Weblogic配置的JNDI 数据源连接
- 如何在vue单页应用中使用百度地图
- 为什么在 Linux 系统中,不建议超频
- python+unnitest时运行后不执行main函数里面的内容
- 【刷题】BZOJ 1413 [ZJOI2009]取石子游戏
- Properties集合概述与存和取
- [Android] Java Basic : preview
- 回测框架pybacktest简介(二)
热门文章
- 一次eureka的事故
- input 模糊搜索下拉框
- Vuex扫描自定义文件夹下的所有文件
- Android集成并开启手写笔识别
- WPF图片的缩放节省内存
- Request processing failed;
- [部署日记]GO在Visual Studio Code初次运行时提示go: go.mod file not found in current directory or any parent directory; see &#39;go help modules&#39;
- Springboot打包部署的步骤
- 删除 gnome自带的Videos软件
- Java基础__04.GUI编程