-
Notifications
You must be signed in to change notification settings - Fork 0
/
Find in Mountain Array.cpp
75 lines (62 loc) · 1.93 KB
/
Find in Mountain Array.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
67
68
69
70
71
72
73
74
75
/**
* // This is the MountainArray's API interface.
* // You should not implement it, or speculate about its implementation
* class MountainArray {
* public:
* int get(int index);
* int length();
* };
*/
class Solution {
public:
int binarySearch(MountainArray mountainArr, int l, int r, int target) {
int mid;
while (l <= r) {
mid = l + (r - l) / 2;
if (mountainArr.get(mid) == target) {
return mid;
} else if (mountainArr.get(mid) > target) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return -1;
}
int reverseBinarySearch(MountainArray mountainArr, int l, int r, int target) {
int mid;
while (l <= r) {
mid = l + (r - l) / 2;
if (mountainArr.get(mid) == target) {
return mid;
} else if (mountainArr.get(mid) > target) {
l = mid + 1;
} else {
r = mid - 1;
}
}
return -1;
}
int findPeak(MountainArray &mountainArr) {
int start = 0;
int end = mountainArr.length() - 1;
while (start < end) {
int mid = start + (end - start) / 2;
if (mountainArr.get(mid) < mountainArr.get(mid + 1)) {
start = mid + 1;
} else {
end = mid;
}
}
return start;
}
int findInMountainArray(int target, MountainArray &mountainArr) {
int n = mountainArr.length();
int peakIndex = findPeak(mountainArr);
int idx = binarySearch(mountainArr, 0, peakIndex, target);
if (idx == -1) {
return reverseBinarySearch(mountainArr, peakIndex, n - 1, target);
}
return idx;
}
};