【问题标题】:Getting max value of a 2D array获取二维数组的最大值
【发布时间】:2016-03-15 03:32:40
【问题描述】:

所以,我想出一个函数来返回存储在二维数组中的最大值时遇到了麻烦。我知道我需要一个 for 循环来遍历 2d 数组,但我很迷茫

class maximum {
   public static void main(String[] args) {
      int[][] table = { {3, 9, 6, 12},
                        {23, -25, 54},
                        {0, -12, 27, 8, 16} };
      System.out.println(getMax(table));  //prints 54
  }
  static int getMax(int[][] A){


     }
}

【问题讨论】:

    标签: java arrays for-loop multidimensional-array


    【解决方案1】:

    你知道你需要什么,那就去做吧。

    static int getMax(int[][] A) {
        int max = 0;
        boolean maxValid = false;
        if (A != null) {
            for (int i = 0; i < A.length; i++) {
                if (A[i] != null) {
                    for (int j = 0; j < A[i].length; j++) {
                        if (!maxValid || max < A[i][j]) {
                            max = A[i][j];
                            maxValid = true;
                        }
                    }
                }
            }
        }
        if (!maxValid) throw new IllegalArgumentException("no elements in the array");
        return max;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-03-04
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      • 2012-10-29
      • 2014-06-28
      • 2016-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多