有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何返回这样一个多维数组

这有点复杂: int[][] generate(int[][] input)创建一个与输入具有相同结构的新数组。 每行的内容都写在下一行。最后一行的内容位于第一行。如果一行的长度对于所有移动的数字来说都太短,则剩余的数字将添加到此行的每个元素上。如果行的长度对于所有移位的数字都太长,则剩余字段将用此行中数字的平均值填充

例如:输入:

int[][] test1 = { {1, 2, 3, -4, -9}, {-20, 13}, {30, 19, 12, -12} }

输出:

{ {30, 19, 12, -12, 12}, {-9, -8}, {-20, 13, -3, -3} }

如果您能给我一些建议,例如我的if语句应该是什么样子,我将非常感激


共 (1) 个答案

  1. # 1 楼答案

    下面是旋转方法的一个可能实现。我在注释中添加了对代码所做操作的解释:

    public static int[][] rotate(int[][] matrix) {
        int[][] result = new int[matrix.length][];
    
        for(int i = 0; i < matrix.length; ++i) {
            // if we exceed the length of the result matrix, let's rotate back to 0 (first row).
            int indexResult = i + 1 == matrix.length ? 0 : i + 1;
            result[indexResult] = new int[matrix[indexResult].length];
    
            // The row in which to insert is shorter than the row to be inserted
            if(result[indexResult].length < matrix[i].length) {
                // Let's find the sum of all the remaining (overflow) numbers.
                int sumNumber = 0;
                for(int j = matrix[i].length - result[indexResult].length - 1; j < matrix[i].length; ++j) {
                    sumNumber += matrix[i][j];
                }
                for(int j = 0; j < result[indexResult].length; ++j) {
                    result[indexResult][j] = matrix[i][j] + sumNumber;
                }
            } else if(result[indexResult].length > matrix[i].length) {  // The row in which to insert is longer
                double average = 0.0;
                int j = 0;
                while(j < matrix[i].length) {
                    average += matrix[i][j];
                    result[indexResult][j] = matrix[i][j];
                    ++j;
                }
                average = average / matrix[i].length;
                while(j < result[indexResult].length) {
                    result[indexResult][j] = (int) average;
                    ++j;
                }
            } else { // The length is the same. just copy the array;
                for(int j = 0; j < matrix[i].length; ++j) {
                    result[indexResult][j] = matrix[i][j];
                }
            }
        }
        return result;
    }
    

    输入:

    int[][] test1 = { {1, 2, 3, -4, -9}, {-20, 13}, {30, 19, 12, -12} };
    

    输出为:

    { {30, 19, 12, -12, 12}, {-9, -8}, {-20, 13, -3, -3} }