-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1901. Find a Peak Element II
48 lines (43 loc) · 1.26 KB
/
1901. Find a Peak Element II
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution
{
int findMaxIndex(int[][] mat, int n, int m, int col)
{
int maxValue = -1;
int index = -1;
for(int i = 0;i<n; i++)
{
if(mat[i][col] > maxValue)
{
maxValue = mat[i][col];
index = i;
}
}
return index;
}
public int[] findPeakGrid(int[][] mat)
{
int n = mat.length;
int m= mat[0].length;
int low = 0, high = m-1;
while(low <= high)
{
int mid = (low + high) / 2;
int maxRowIndex = findMaxIndex(mat, n, m, mid);
int left = mid - 1 >= 0 ? mat[maxRowIndex] [mid - 1] : -1;
int right = mid + 1 < m ? mat[maxRowIndex] [mid+1] : -1;
if(mat[maxRowIndex] [mid] > left && mat[maxRowIndex] [mid] > right)
{
return new int[]{maxRowIndex, mid};
}
else if (mat[maxRowIndex] [mid] < left)
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
return new int[]{-1,-1};
}
}