-
Notifications
You must be signed in to change notification settings - Fork 0
/
Find in Mountain Array.cpp
45 lines (45 loc) · 1.5 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
class Solution {
public:
int findInMountainArray(int target, MountainArray& mountainArr) {
int length = mountainArr.length();
int peakIndex = findPeakIndex(1, length - 2, mountainArr);
int increasingIndex =
binarySearch(0, peakIndex, target, mountainArr, false);
if (mountainArr.get(increasingIndex) == target)
return increasingIndex;
int decreasingIndex =
binarySearch(peakIndex + 1, length - 1, target, mountainArr, true);
if (mountainArr.get(decreasingIndex) == target)
return decreasingIndex;
return -1;
}
int findPeakIndex(int low, int high, MountainArray& mountainArr) {
while (low != high) {
int mid = low + (high - low) / 2;
if (mountainArr.get(mid) < mountainArr.get(mid + 1)) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
int binarySearch(int low, int high, int target, MountainArray& mountainArr,
bool reversed) {
while (low != high) {
int mid = low + (high - low) / 2;
if (reversed) {
if (mountainArr.get(mid) > target)
low = mid + 1;
else
high = mid;
} else {
if (mountainArr.get(mid) < target)
low = mid + 1;
else
high = mid;
}
}
return low;
}
};