首页 > 基础资料 博客日记

java稀疏数组

2023-07-24 17:39:57基础资料围观194

这篇文章介绍了java稀疏数组,分享给大家做个参考,收藏Java资料网收获更多编程知识

import java.lang.reflect.Array;
import java.util.Scanner;
import java.util.Arrays;

public class test1 {

    public static void main(String[] args) {
        int[][] arr1 = new int[11][11];
        arr1[1][2]=1;
        arr1[2][3]=2;
        int sum = get_sum(arr1);

        System.out.println("这是原始数组");
        System.out.println("========================");
        print(arr1);

        System.out.println("转化为稀疏数组");
        System.out.println("========================");

        int[][] arr2 = new int[sum+1][3];
        arr2[0][0]=11;
        arr2[0][1]=11;
        arr2[0][2]=sum;
        vlaue(arr1,arr2);
        print(arr2);
        System.out.println("还原");
        System.out.println("========================");
        int[][] arr3 = new int[11][11];
        back(arr3,arr2);
        print(arr3);


}
    //打印数组
    public  static  void  print(int[][] arr){
        for (int i=0;i<arr.length;i++){
            for (int j=0;j<arr[0].length;j++){
                System.out.print(arr[i][j]+"\t");
            }
            System.out.println();
        }
    }



    //获取有效数据的个数
    public  static  int  get_sum(int[][] arr){
        int sum=0;
        for (int i=0;i<arr.length;i++){
            for (int j=0;j<arr[0].length;j++){
                if (arr[i][j]!=0){sum++;}
            }

        }
        return sum;
    }



    //为稀疏数组赋值
    public  static  void  vlaue(int[][] arr1,int[][] arr2){

        int count = 1;
        for (int i=0;i<arr1.length;i++){
            for (int j=0;j<arr1[0].length;j++){
                if (arr1[i][j]!=0){
                    arr2[count][0]=i;
                    arr2[count][1]=j;
                    arr2[count][2]=arr1[i][j];
                    count++;
                }
            }
        }
    }

//还原
public  static  void  back(int[][] arr1,int[][] arr2){
    for (int i=1;i<arr2.length;i++){

            arr1[arr2[i][0]][arr2[i][1]]=arr2[i][2];
        }
    }
}




输出:
    这是原始数组
========================
0	0	0	0	0	0	0	0	0	0	0	
0	0	1	0	0	0	0	0	0	0	0	
0	0	0	2	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
转化为稀疏数组
========================
11	11	2	
1	2	1	
2	3	2	
还原
========================
0	0	0	0	0	0	0	0	0	0	0	
0	0	1	0	0	0	0	0	0	0	0	
0	0	0	2	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	

Process finished with exit code 0


文章来源:https://www.cnblogs.com/clinch/p/16497662.html
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐

标签云