forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
find-peak-element.cpp
60 lines (52 loc) · 1.34 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
// Time: O(logn)
// Space: O(1)
class Solution {
public:
/**
* @param A: An integers array.
* @return: return any of peek positions.
*/
int findPeak(vector<int> A) {
int left = 1;
int right = A.size() - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (A[mid - 1] <= A[mid] && A[mid] >= A[mid + 1]) {
return mid;
} else if (A[mid - 1] > A[mid]) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
};
class Solution2 {
public:
/**
* @param A: An integers array.
* @return: return any of peek positions.
*/
int findPeak(vector<int> A) {
int l = 0;
int r = A.size() - 1;
while (l < r) {
int mid = l + (r - l) / 2;
// If mid is a peak
if ((mid == 0 || A[mid - 1] <= A[mid]) &&
(mid == A.size() - 1 || A[mid] >= A[mid + 1])) {
return mid;
}
// If mid - 1 is a possible peak
else if (mid > 0 && A[mid - 1] > A[mid]) {
r = mid - 1;
}
// Else: A[mid - 1] <= A[mid] < A[mid + 1]
else {
l = mid + 1;
}
}
return l;
}
};