-
Notifications
You must be signed in to change notification settings - Fork 1
/
Find Peak Element.cpp
66 lines (53 loc) · 1.5 KB
/
Find 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//Approach-1 (Simple binary search)
class Solution {
public:
int findPeakElement(vector<int>& nums) {
int n = nums.size();
int l = 0, r = n-1;
while(l < r) {
int mid = l + (r-l)/2;
if(nums[mid] < nums[mid+1])
l = mid+1;
else
r = mid;
}
return l;
}
};
//Approach-2 (More intuitive)
class Solution {
public:
int findPeakElement(vector<int> &A) {
int n = A.size();
if(n == 1)
return 0;
if(A[0] > A[1]) return 0;
if(A[n-1] > A[n-2]) return n-1;
int l = 1, r = n-2; //since, we already checked for 0 and (n-1) indices above
int mid;
/*
case-1:
mid(peak)
/\
.../ \...
case-2:
(peak)
/\
.../ \mid...
case-3:
(peak)
/\
...mid/ \...
*/
while(l < r) {
mid = l + (r-l)/2;
if(A[mid] > A[mid-1] && A[mid] > A[mid+1]) //1. mid is PEAK
return mid;
if(A[mid] < A[mid-1]) //2. mid is right to PEAK. So, go towards left
r = mid-1;
else if(A[mid] < A[mid+1]) //3. mid is left to PEAK. So, go towards right
l = mid+1;
}
return l;
}
};