LC.P1901[寻找峰值II]

方法一:二分查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public int[] findPeakGrid(int[][] mat) {
int m = mat.length;
int left = 0, right = m - 1;
while (left < right) {
int i = left + right >> 1;
int j = maxPos(mat[i]);
if (mat[i][j] > mat[i + 1][j]) right = i;
else left = i + 1;
}
return new int[]{left, maxPos(mat[left])};
}

private int maxPos(int[] nums) {
int p = 0;
for (int i = 0; i < nums.length; ++i) {
if (nums[p] < nums[i]) {
p = i;
}
}
return p;
}
}
  • 时间复杂度:$O(nlogm)$
  • 空间复杂度:$O(1)$