Home  >  Article  >  Java  >  How to convert sparse array and two-dimensional array in Java?

How to convert sparse array and two-dimensional array in Java?

王林
王林forward
2023-04-21 10:22:081439browse

Stop talking nonsense and go directly to the code

package com.malajava.sparsearray;

public class SparseArray {

    public static void main(String[] args) {
        //创建一个11*11二维数组
        int array[][] = new int[11][11];
        array[1][2]=1;
        array[2][3]=2;
        System.out.println("------------------二维数组------------------");
        for (int[]row:array){
            for (int data: row){
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }

        //二维数组转稀疏数组
        //先遍历二维数组,得到非零数据的个数
        int sum=0;
        for (int[]row:array){
            for (int data: row){
                if(data != 0)
                    sum++;
            }
        }
        System.out.println("----------------------------------------");
        System.out.println("非零个数为:"+sum);
        int sparseArray[][] = new int[sum+1][3];
       sparseArray[0][0] =11;
       sparseArray[0][1]=11;
       sparseArray[0][2]=sum;
       //遍历二维数组将非零数字存入稀疏数组
        int count=0;        //用于记录是第几个非零数据
        for (int i=0;i<p> Running results: <img src="https://img.php.cn/upload/article/000/465/014/168204373194330.jpg" alt="How to convert sparse array and two-dimensional array in Java?"></p>

The above is the detailed content of How to convert sparse array and two-dimensional array in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete