Java - 2d array.length:如何使循环通过列而不是行?

时间:2013-03-01 09:48:45

标签: java arrays multidimensional-array symmetric

 public static int[] getMinimumSymmetricOfEveryRow (int [][] A)
{
    int min = Integer.MAX_VALUE;
    int[] arr=new int[A.length];
    for (int i = 0; i < A.length; i++){
        for (int j = 0; j < A[i].length; j++){
            if (A[i][j] < min && isSymmetric(A[i][j])){
                arr[i] = A[i][j];
                }
        }
    }
    return arr;
}

这是我的函数,它从2D数组中的每一行返回min对称元素的数组。它适用于array [n] [n],但不适用于array [m] [n] ...... (它返回m个元素而不是n)。我不知道是什么问题??

1 个答案:

答案 0 :(得分:0)

假设输入数组的格式为[row] [column],方法应为 getMinimumSymmetricOfEveryColumn ,您可以将方法编写为:

 public static int[] getMinimumSymmetricOfEveryColumn(int[][] matrix) {
    int[] columnMinimum = new int[matrix[0].length];
    for (int colimnIndex = 0; colimnIndex < matrix[0].length; colimnIndex++){
        int currentMinimum = Integer.MAX_VALUE;
        for (int rowIndex = 0; rowIndex < matrix.length; rowIndex++){
            int currentElement = matrix[rowIndex][colimnIndex];
            if (currentElement < currentMinimum && isSymmetric(currentElement)){
                columnMinimum[colimnIndex] = currentElement;
            }
        }
    }
    return columnMinimum;
}