[英]Java - Find max element of every row and max element of every column on 2D Array
我想通过逐行检查和列相同来查找行的max元素!
示例2D阵列:
3 7 2 5 1 4 6 9 8
通过逐个元素地检查每个行,它应该像这样:在第一行中,第7行是max,然后在第二行中,没有任何元素大于7,因此max仍然是7,然后在第三行中,第9行大于7,因此max行的元素是9!
然后,对列也相同:第一列为6,然后第二列为9,而第三列没有元素大于9,因此列的最大值为9!
从理论上说,行的最大元素也是列的最大元素!
因此,我需要制作一个做到这一点的Java程序,以便最大行数和最大列数的结果相等,这意味着我的程序可以正确运行!
在我的代码中,我已将2D数组存储在bigMatrix[][]
,但我不知道如何使用bigMatrix[i]
整行,它可以工作,但我不知道如何,我不知道不知道如何做同样的事情来获取每一列并将它们作为数组传递给我的函数getMax()
以找到该列的最大值!
**以下代码可以很好地找到Rows的max元素,但是我不知道如何找到Columns的max元素!
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;
}
只需将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];
}
}
为此,创建一个循环,将每一列解析为findMaxMethod,如下所示:
public int method(int column)
{
int result = Integer.MIN_VALUE;
for(int x = 0; x<array[column].length; x++)
{
result = Math.max(result, array[column][x]);
}
return result;
}
希望这可以帮助....
这是您问题的解决方案,假设数组中的每一行具有相同的列数(请注意,需要考虑以下情况:(1)当数组为null时,(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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.