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

稀疏数组

时间:2022-08-29 20:11:09浏览次数:41  
标签:int System 稀疏 a1 a2 数组 out

1.当一个数组中大部分元素为0,或者为同一值的数组时,可以使用稀疏数组来保存该数组。

2.处理方式为

记录数组共几行几列

把具有不同值的元素和行列及值记录在一个小规模数组中,从而缩小程序的规模

public class ArrayDemo03 {
public static void main(String[] args) {
int[][]a1=new int[11][11];
a1[1][2]=1;
a1[2][3]=1;
System.out.println("输出原始数组");
for (int[] ints : a1) {
for (int anInt : ints) {
System.out.print(anInt+"\t");

}
System.out.println();
}
//转换为稀疏数组保存;
int sum=0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if(a1[i][j]!=0){
System.out.println("第"+i+"行"+"第"+j+"列"+" "+a1[i][j]);
sum+=1;
}

}

}
System.out.println("共"+sum+"个有效数字");
//创建一个稀疏数组
int[][] a2=new int[sum+1][3];
a2[0][0]=11;
a2[0][1]=11;
a2[0][2]=sum;
//遍历二维数组,将非0值,存放在二维数组中
int count=0;
for (int i = 0; i < a1.length; i++) {
for (int j = 0; j < a1[i].length; j++) {
if(a1[i][j]!=0){
count++;
a2[count][0]=i;
a2[count][1]=j;
a2[count][2]=a1[i][j];



}

}

}
System.out.println("输出稀疏数组");
for (int[] ints : a2) {
for (int anInt : ints) {
System.out.print(anInt+"\t");

}
System.out.println();
}
}

}

标签:int,System,稀疏,a1,a2,数组,out
From: https://www.cnblogs.com/zlsame/p/16637201.html

相关文章

  • numpy 数组 浅拷贝 地址
    对于numpy数组:importnumpyasnpa=np.array([1,2,3,4])b=a[0:2]b[0]=np.sum(a[:])/4修改b[0]的值会改变a的值,原因:https://blog.csdn.net/AManFromEarth/arti......
  • 数组
    1.长度是固定的,一旦被创建,大小就不能改变。2.元素类型必须相同。3.数据元素可以是任何数据类型,包括基本类型和引用类型。4..数组变量本身属于引用类型,也可以看出是对象,......
  • leetcode 每日一题 1470. 重新排列数组
    leetcode 每日一题 1470.重新排列数组classSolution{publicint[]shuffle(int[]nums,intn){int[]arr=newint[nums.length];for(......
  • 【leetcode】81. 搜索旋转排序数组 II
    原题地址:https://leetcode.cn/problems/search-in-rotated-sorted-array-ii/用循环遍历数组肯定能轻松找到target但要尽可能减少操作步骤,一般跟顺序有关的都是用二分,关键......
  • maybe_serialize() | WordPress序列化数据/数组/对象
    函数maybe_serialize(string|array|object$data)描述该WordPress函数可将数组/对象/字符串序列化。参数$data,(string|array|object)需要序列化的数据。返回值(m......
  • C++ 多维数组的访问
    1.可以把一维数组想象成一排士兵,把二维数组想象成一个士兵方阵,把三维数组想象成多个士兵方阵。这样,当你要找其中的一个士兵时,你只要知道他在哪个方阵(从0、1、2中选择),在哪......
  • 数组方法中 push() 和 unshift() 的区别
    数组方法有很多,而且用到的频率也是很高,特别是push()方法,而与之对应的另一个方法就是unshift(),那么这两个方法有什么区别呢??......
  • 刷题篇。树、图、数组等相关常见处理操作
    一、树 序号做什么方法伪码 1前、中、后遍历    2以任意节点为根重构树    ......
  • leetcode-1470. 重新排列数组
    1470.重新排列数组图床:blogimg/刷题记录/leetcode/1470/刷题代码汇总:https://www.cnblogs.com/geaming/p/16428234.html题目思路开辟新的空间,装入元素。解法class......
  • 删除有序数组中的重复项
    目录题目描述解题思路解题代码题目描述题目地址:https://leetcode.cn/problems/remove-duplicates-from-sorted-array/题目要求给你一个升序排列的数组nums,请你......