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

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

王林
Release: 2023-04-21 10:22:08
forward
1533 people have browsed it

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>
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
Install JAVA
From 1970-01-01 08:00:00
0
0
0
Unable to install java
From 1970-01-01 08:00:00
0
0
0
Can java be used as the backend of the web?
From 1970-01-01 08:00:00
0
0
0
Is this in Java language?
From 1970-01-01 08:00:00
0
0
0
Help: JAVA encrypted data PHP decryption
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template