-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path1095.cpp
More file actions
49 lines (48 loc) · 1.53 KB
/
1095.cpp
File metadata and controls
49 lines (48 loc) · 1.53 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* // 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 target, MountainArray &mountainArr) {
int n = mountainArr.length();
int left = 0;
int right = n - 1;
while (left < right) {
int mid = left + (right - left) / 2;
int midValue = mountainArr.get(mid);
int nextValue = mountainArr.get(mid + 1);
if (midValue > nextValue) right = mid;
else left = mid + 1;
}
int maxIndex = left;
if (mountainArr.get(maxIndex) == target) return maxIndex;
if (mountainArr.get(maxIndex) < target) return -1;
// find left part
left = 0;
right = maxIndex;
while (left < right) {
int mid = left + (right - left) / 2;
int midValue = mountainArr.get(mid);
if (target <= midValue) right = mid;
else left = mid + 1;
}
if (mountainArr.get(left) == target) return left;
// find right part
left = maxIndex;
right = n - 1;
while (left < right) {
int mid = left + (right - left) / 2;
int midValue = mountainArr.get(mid);
if (target >= midValue) right = mid;
else left = mid + 1;
}
if (mountainArr.get(left) == target) return left;
return -1;
}
};