如何返回包含二维数组中最小值的列id (Java)



我试图返回包含矩阵中最小值的列的索引,但到目前为止我只能返回矩阵的最小值,并且无法弄清楚如何返回该列的id。如果我尝试返回"col",它不会改变任何东西。

public static int minColIndex (int[][] m) {
        int row = m.length, col = m[0].length; 
        int min = m[0][0]; 
        for (col = 0; col < m.length; col++) {
            for (row = 0; row < m[col].length; row++) {
                if (min > m[col][row]) {
                    min = m[col][row];
                }
            }
        }
        return min; 
    }

在您的代码中,在外部循环完成后,col的值始终是m.length - 1。您需要将最小列存储在某个地方,例如

public static int minColIndex (int[][] m) {
    int row = m.length, col = m[0].length; 
    int min = m[0][0]; 
    int minCol = 0; // extra variable to store minimumm column
    for (col = 0; col < m.length; col++) {
        for (row = 0; row < m[col].length; row++) {
            if (min > m[col][row]) {
                min = m[col][row];
                minCol = col; // remember the minimum column as well as minimum
            }
        }
    }
    return minCol; // return minimum column, not col
}

也不需要在循环之前设置rowcol的初始值,因此您可以将方法的前几行更改为以下内容,以便更清晰:

public static int minColIndex (int[][] m) {
    int min = m[0][0]; 
    int minCol = 0; // extra variable to store minimumm column
    for (int col = 0; col < m.length; col++) {
        for (int row = 0; row < m[col].length; row++) {
        ... etc.
public static int minColIndex (int[][] m) {
        int row = m.length, col = m[0].length , int index = 0; 
        int min = m[0][0]; 
        for (col = 0; col < m.length; col++) {
            for (row = 0; row < m[col].length; row++) {
                if (min > m[col][row]) {
                    min = m[col][row];
                    index= col;
                }
            }
        }
        return index; 
    }

If(minmin = [c] [r];
保存= c;
} '

定义这些变量。

int rowOfMinValue = 0;
int colOfMinValue = 0;

然后,

改变:

if (min > m[col][row]) {
    min = m[col][row];
}

:

if (min > m[col][row]) {
    min = m[col][row];
    rowOfMinValue = row;
    colOfMinValue = col;
}

现在,你有最小值的行和列在手。

:你在矩阵中错误地指向rowcol。在m x n矩阵上,mn分别表示。因此,在m[][]矩阵中,每个[]依次代表rowcol

如果value 62nd row, 4th col中,那么我们写为

row=1; 
col=3; 
value = 6; 
m[ row ][ col ] = value;

最新更新