-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1095.cpp
More file actions
51 lines (50 loc) · 1.21 KB
/
1095.cpp
File metadata and controls
51 lines (50 loc) · 1.21 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
50
51
/**
* // 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 l = 0, h = mountainArr.length()-1;
int m , maxidx;
while(l<h){
m = l + (h-l)/2;
if(mountainArr.get(m)<mountainArr.get(m+1))
l = m + 1;
else
h = m;
}
maxidx = l;
// first half
l = 0;
h = maxidx;
while(l<h){
m = l + (h-l)/2;
if(target<=mountainArr.get(m))
h = m ;
else
l = m + 1;
}
if(mountainArr.get(l)==target)
return l;
//second half
l = maxidx+1;
h = mountainArr.length()-1;
while(l<h){
m = l + (h-l)/2;
if(target<mountainArr.get(m))
l = m + 1;
else
h = m;
}
if(mountainArr.get(l)==target)
return l;
//not found
return -1;
}
};