我在想使用Java时。
有二维数组,如下所示。
int[][] test = {{3, 9, 3, 5}, {4, 19, 4, 9}, {2, 10, 5, 6}};
我想在二维数组的每一行中找到最大值,并且我想知道如何对其进行编码。
我想要的结果是
int[] answer = {4, 19, 5, 9}
只需添加评论,我想提取最大的价值。
[0][0] = 3;
[1][0] = 4;
[2][0] = 2;
[0][1] = 9;
[1][1] = 19;
[2][1] = 10;
[0][2] = 3;
[1][2] = 4;
[2][2] = 5;
[0][3] = 5;
[1][3] = 9;
[2][3] = 6;
So max value is 4, 19, 5, 9
我尝试了这种方法,但是这种方法是arr [i] [j],它比较二维数组中的所有元素,并且在比较中仅找到max。
for (int i = 0; i < test.length; i++) {
int max = test[i][0];
for (int j = 0; j < test[i].length; j++)
if (test[i][j] > max)
max = test[i][j]
}
您可以从第一行初始化结果,然后在此矩阵上进行迭代(如果当前元素test[row][column]
大于)result[column]
,则重新分配result[column]
:
public static void main(String[] args) {
int[][] test = {{3, 9, 3, 5}, {4, 19, 4, 9}, {2, 10, 5, 6}};
int[] result = test[0];
for (int row = 1; row < test.length; row++) {
for (int column = 0; column < test[0].length; column++) {
if (test[row][column] > result[column]) {
result[column] = test[row][column];
}
}
}
for (int number : result) {
System.out.print(number + " "); // 4 19 5 9
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句