2016-03-15 132 views
1

所以,我遇到了一個函數,它將返回存儲在二維數組中的最大值。我知道我需要一個循環遍歷二維數組,但我很迷茫獲取二維數組的最大值

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){ 


    } 
} 

回答

0

你知道你需要什麼,所以這樣做。

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