1 class Solution: 2 """ 3 @param: A: An integer matrix 4 @return: The index of the peak 5 """ 6 def findPeakII(self, A): 7 # write your code here 8 m, n = len(A), len(A[0]) 9 left, right, up, down = 1, n - 2, 1, m - 2 10 while left + 1 < right and up + 1 < down: 11 if right - left > down - up: 12 mid = (left + right) // 2 13 max_index = self.find_max_in_col(A, mid, up, down) 14 if self.is_peak(A, max_index, mid): 15 return [max_index, mid] 16 elif A[max_index][mid] < A[max_index][mid - 1]: 17 right = mid 18 else: 19 left = mid 20 else: 21 mid = (up + down) // 2 22 max_index = self.find_max_in_row(A, mid, left, right) 23 if self.is_peak(A, mid, max_index): 24 return [mid, max_index] 25 elif A[mid][max_index] < A[mid - 1][max_index]: 26 down = mid 27 else: 28 up = mid 29 for i in range(up, down + 1): 30 for j in range(left, right + 1): 31 if self.is_peak(A, i, j): 32 return [i, j] 33 return [-1, -1] 34 35 def is_peak(self, A, i, j): 36 return A[i][j] == max(A[i][j], A[i - 1][j], A[i + 1][j], A[i][j - 1], A[i][j + 1]) 37 38 def find_max_in_col(self, A, col, up, down): 39 index = down 40 for i in range(up, down): 41 if A[i][col] > A[index][col]: 42 index = i 43 return index 44 45 def find_max_in_row(self, A, row, left, right): 46 index = right 47 print(left, right) 48 for i in range(left, right): 49 if A[row][i] > A[row][index]: 50 index = i 51 return index