Java 用1方法理解增加最大元素的逻辑
此方法的任务是在数组arr中的最大元素上增加或添加1。如果相同的最大元素在数组中出现多次,则最后一次出现的元素应增加。(“Last”指下标最大的行中的一个,如果该行中有多个最大元素出现,则指下标最大的列中的一个。)该方法不应进行任何不必要的工作或计算。请注意,数组的行可能有不同数量的元素 解决方案:Java 用1方法理解增加最大元素的逻辑,java,arrays,Java,Arrays,此方法的任务是在数组arr中的最大元素上增加或添加1。如果相同的最大元素在数组中出现多次,则最后一次出现的元素应增加。(“Last”指下标最大的行中的一个,如果该行中有多个最大元素出现,则指下标最大的列中的一个。)该方法不应进行任何不必要的工作或计算。请注意,数组的行可能有不同数量的元素 解决方案: public static void incrMax(int[][] arr) { int maxRow = 0; int maxCol = 0; boolean found
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[]mat){
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]++;
}
}
}
//将每行的最大值增加一
对于(int i=0;i if(maxRow)如果没有检查值,则设置maxRow
和maxCol
。否则,检查当前值是否大于先前的最大值。如果设置了它们,则检查。此外,您的找到的
检查应位于循环之后(外部)。
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]++;
}
}
}