-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path1095.cpp
More file actions
34 lines (33 loc) · 1.1 KB
/
1095.cpp
File metadata and controls
34 lines (33 loc) · 1.1 KB
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
__________________________________________________________________________________________________
/**
* // 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 findInMountainArray(int t, MountainArray& arr) {
auto peak = 0, r = arr.length() - 1;
while (peak < r) {
int m = (peak + r) / 2;
if (arr.get(m) > arr.get(m + 1)) r = m;
else peak = m + 1;
}
auto i = bSearch(arr, t, 0, peak);
return i != -1 ? i : bSearch(arr, t, peak + 1, arr.length() - 1, false);
}
int bSearch(MountainArray& arr, int t, int l, int r, bool asc = true) {
while (l < r) {
int m = (l + r) / 2;
if ((asc && arr.get(m) < t) || (!asc && arr.get(m) > t)) l = m + 1;
else r = m;
}
return arr.get(l) == t ? l : -1;
}
};
__________________________________________________________________________________________________
__________________________________________________________________________________________________