简体   繁体   中英

Understanding the logic of a increase max element by 1 method

The duty of this method is to increment or add 1 to, the largest element in the array arr. If the same largest element is present more than once in the array, the last occurrence should be incremented. ("Last" means the one in the row with the largest subscript, and the one with the largest column subscript if there is more than one occurrence of the largest element in that row.) The method should not do any unnecessary work or computation. Note that the array's rows may have different numbers of elements.

Solution:

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;
            }
        }
    }
}

What I understand is that we would want to create two int's to store the maximum elements for horizontal rows and vertical columns. In order to seek those values out we need to loop the 2D-array. I am particularly confused by nested for-loops and 2d arrays. And the line:

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

Can someone please walk through the logic of this code?

Thank you

 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]++;
            }

        }
    }

this will do the work you are asking for

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM