-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFind_a_peak_element.cpp
48 lines (46 loc) · 1.27 KB
/
Find_a_peak_element.cpp
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
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int FindMaxIndex(vector<vector<int>>& mat, int n, int m, int col)
{
int maxValue = -1;
int index = -1;
for(int i = 0; i < n; i++)
{
if(maxValue < mat[i][col])
{
maxValue = mat[i][col];
index = i;
}
}
return index;
}
vector<int> findPeakGrid(vector<vector<int>>& mat) {
int n = mat.size();
int m = mat[0].size();
int low = 0;
int 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 {maxRowIndex, mid};
}
else if(mat[maxRowIndex][mid] < left)
{
high = mid -1;
}
else
{
low = mid +1;
}
}
return {-1, -1};
}
};