-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1095.cpp
More file actions
68 lines (61 loc) · 1.56 KB
/
1095.cpp
File metadata and controls
68 lines (61 loc) · 1.56 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* // 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 find_peak(MountainArray &mountainArr)
{
int l=0, r=mountainArr.length()-1;
while(l<=r)
{
int m=(l+r)/2;
int m_val=mountainArr.get(m);
int m_r_val=mountainArr.get(m+1);
if(m_val<m_r_val) {
l=m+1;
} else {
r=m-1;
}
}
return l;
}
int findInMountainArray(int target, MountainArray &mountainArr)
{
int peak=find_peak(mountainArr);
int l=0, r=peak;
if(mountainArr.get(l)<=target&&mountainArr.get(r)>=target)
while(l<=r)
{
int m=(l+r)/2;
int val=mountainArr.get(m);
if(val==target)
return m;
else if(val<target)
l=m+1;
else
r=m-1;
}
l=peak;
r=mountainArr.length()-1;
if(mountainArr.get(r)<=target&&mountainArr.get(l)>=target)
while(l<=r)
{
int m=(l+r)/2;
int val=mountainArr.get(m);
if(val==target)
return m;
else if(val<target)
r=m-1;
else
l=m+1;
}
return -1;
}
};