Java - 查找2D数组上每列的最大元素和每列的最大元素

时间:2018-03-15 17:25:41

标签: java arrays multidimensional-array

我希望通过逐行检查来找到行的最大元素,对于列来说是相同的!

示例2D数组:

3 7 2 5 1 4 6 9 8

通过按元素检查每一行,它应该是这样的:在第一行7是max,然后在第二行没有大于7的元素所以max仍然是7,然后在第三行9大于7所以行的最大元素是9!

然后对于列相同:6在第一列上是max,然后在第二列9上是max,在第三列上没有大于9的元素,因此列的最大值是9!

理论上,行的最大元素也是列的最大元素!

所以,我需要创建一个Java程序,这样最大行和最大列的结果将是相等的,这意味着我的程序正确运行!

在我的代码中,我已将我的2D数组存储在bigMatrix[][]上,但我不明白如何用bigMatrix[i]取整行,它有效,但我不明白,我不知道如何做同样的事情来取每一列并将它们作为数组传递给我的函数getMax()以找到该列的最大值!

**以下代码适用于查找行的最大元素,但我不知道如何找到列的最大元素!

int rowMax = Integer.MIN_VALUE;

for(int i = 0; i < 3; i++) {
    if(rowMax < getMax(bigMatrix[i])) {
        rowMax = getMax(bigMatrix[i]);
    }
}

public static int getMax(int[] ourArray) {
    int max = Integer.MIN_VALUE;
    for (int i = 0; i < ourArray.length; i++) {
        max = Math.max(max, ourArray[i]);
    }
    return max;
}

3 个答案:

答案 0 :(得分:0)

只需将getMax(int[] ourArray)函数的参数类型更改为getMax(int[][] ourArray),然后在调用函数时将2D数组作为参数传递。

在正文中你需要遍历数组中的每个项目,因此你需要双循环

for(int i = 0; i < ourArray.length;i++){
 for(int j = 0; j < ourArray[i].length;j++){
  max = Math.max(max, ourArray[i][j];
 }
}

答案 1 :(得分:0)

为此创建一个循环,将每个列解析为findMaxMethod 喜欢这个:

b
希望这会有所帮助......

答案 2 :(得分:0)

这里是解决您的问题的方法,假设数组中的每一行具有相同的列数(请注意,需要考虑以下情况:(1)当数组为空时,以及(2)当数组不为null并且其中没有项目时;以下两种方式都适当地处理这两种情况):

public static void findAndPrintMaximumValues(int[][] arrayToTraverse) {
        if(arrayToTraverse == null || arrayToTraverse.length == 0 || arrayToTraverse[0].length == 0) {  
            throw new IllegalArgumentException("Either the array is null or it doesn't contain any elements.");
        }

        int maximumValueGoingRowByRow = Integer.MIN_VALUE;
        int maximumValueGoingColumnByColumn = Integer.MIN_VALUE;

        // Traverse the array in row-major order.
        for(int currentRowIndex = 0; currentRowIndex < arrayToTraverse.length; currentRowIndex++) {
            for(int currentColumnIndex = 0; currentColumnIndex < arrayToTraverse[0].length; currentColumnIndex++) {
                maximumValueGoingRowByRow = Math.max(maximumValueGoingRowByRow, arrayToTraverse[currentRowIndex][currentColumnIndex]);
            }
        }

        // Traverse the array in column-major order.
        for(int currentColumnIndex = 0; currentColumnIndex < arrayToTraverse[0].length; currentColumnIndex++) {
            for(int currentRowIndex = 0; currentRowIndex < arrayToTraverse.length; currentRowIndex++) {
                maximumValueGoingColumnByColumn = Math.max(maximumValueGoingColumnByColumn, arrayToTraverse[currentRowIndex][currentColumnIndex]);
            }
        }

        System.out.format("The maximum value with traversal in row-major order is %d.%n", maximumValueGoingRowByRow);
        System.out.format("The maximum value with traversal in column-major order is %d.", maximumValueGoingColumnByColumn);
    }