简体   繁体   English

Java将二维数组转换为一维数组

[英]Convert two dimensional array to one dimensional array in Java

I'm trying to convert a two-dimensional array to a one-dimensional array in Java.我正在尝试将二维数组转换为 Java 中的一维数组。 I cannot use any additional data structures, ArrayLists, collections etc. for temporary storage.我不能使用任何额外的数据结构、ArrayLists、集合等作为临时存储。 Only one array can be allocated - the one that will be returned from the method.只能分配一个数组 - 将从该方法返回的数组。

There are three tests with arrays inputed into the method to validate the program.共有三个测试,其中将数组输入到方法中以验证程序。 Test one has a 2D array with 3 rows and columns, test two has a 2D array with 3 rows and 1 column, and test three is empty.测试一有一个 3 行和列的二维数组,测试二有一个 3 行 1 列的二维数组,测试三为空。

My current code is:我目前的代码是:

public static int[] twoDConvert(int[][] nums) {
    int index = 0;
    int[] combined = new int[nums.length*3];
    if (nums.length == 0) return combined;  
        for (int row = 0; row < nums.length; row++) {
            for (int col = 0; col < nums.length; col++) {
                combined[index] += nums[row][col];
                index++;
        }
    }
    return combined;
}

The first test works correctly, but for some reason the 2nd test throws ArrayIndexOutOfBoundsException (Index 1 out of bounds for length 1).第一个测试工作正常,但由于某种原因,第二个测试抛出 ArrayIndexOutOfBoundsException(长度为 1 的索引 1 越界)。 This occurs no matter how large or small the combined array length is.无论组合数组长度有多大或多小,都会发生这种情况。 How can I fix this?我怎样才能解决这个问题?

We create a single Integer array with a length determines by the size method.我们创建一个长度由 size 方法确定的 Integer 数组。 Size takes the 2-dimensional array and finds the sum of all columns in each row and returns that sum. Size 获取二维数组并找到每行中所有列的总和并返回该总和。 We check if the length is 0, and if so, we return.我们检查长度是否为 0,如果是,则返回。 We then loop through all rows, followed by a loop through all columns in that row.然后我们循环遍历所有行,然后循环遍历该行中的所有列。 We then assign the value at that row and column to that next index in the array.然后我们将该行和列的值分配给数组中的下一个索引。 Unfortunately we can't do any math (to my knowledge) to determine the index based of row/column since they could be variable sizes.不幸的是,我们无法做任何数学运算(据我所知)来确定基于行/列的索引,因为它们可能是可变大小。

    public static int[] twoDConvert(int[][] nums) {
        int[] combined = new int[size(nums)];

        if (combined.length <= 0) {
            return combined;
        }
        int index = 0;

        for (int row = 0; row < nums.length; row++) {
            for (int column = 0; column < nums[row].length; column++) {
                combined[index++] = nums[row][column];
            }
        }
        return combined;
    }

    private static int size(int[][] values) {
        int size = 0;

        for (int index = 0; index < values.length; index++) {
            size += values[index].length;
        }
        return size;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM