通过1种方法

时间:2017-02-03 23:18:21

标签: java arrays

此方法的任务是增加或添加1到数组arr中的最大元素。如果在数组中多次出现相同的最大元素,则最后一次出现应该递增。 (“Last”表示具有最大下标的行中的那个,如果该行中存在多个最大元素,则表示具有最大列下标的那个。)该方法不应该执行任何不必要的工作或计算。请注意,数组的行可能包含不同数量的元素。

解决方案:

public static void incrMax(int[][] arr) {
    int maxRow = 0;
    int maxCol = 0;
    boolean found = false;
    for(int row = 0; row < arr.length; row++) {
        for(int col = 0; col < arr[row].length; col++) {
            if(!found || arr[row][col] >= arr[maxRow][maxCol] {
                maxRow = row;
                maxCol = col;
                found = true;
            }
            if(found) {
                arr[maxRow][maxCol] += 1;
            }
        }
    }
}

我的理解是我们想要创建两个int来存储水平行和垂直列的最大元素。为了寻找这些值,我们需要循环2D数组。我对嵌套的for循环和2d数组特别困惑。这一行:

if(!found || arr[row][col] >= arr[maxRow][maxCol]

有人可以介绍一下这段代码的逻辑吗?

谢谢

1 个答案:

答案 0 :(得分:0)

 void increment(int[][] mat) {
        //increment the max of every row by one 
        for (int i = 0; i < mat.length; i++) {
            int maxRow = 0, maxIndex = -1;
            for (int j = 0; j < mat[i].length; j++) {
                if (maxRow <= mat[i][j]) { // to allow multiple occurences of the same value i used <= 
                    maxRow = mat[i][j];
                    maxIndex = j;
                }
            }

            //we check if a max is found
            if (maxIndex != -1) {
                mat[i][maxIndex]++;
            }

        }
    }

这将完成你要求的工作