-
Notifications
You must be signed in to change notification settings - Fork 0
/
Find in Mountain Array.cpp
64 lines (63 loc) · 1.53 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* // 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 low=0;
int high=n-1;
int peak=-1;int temp=-1;
while(low<=high)
{
int mid=low+(high-low)/2;
int x=mountainArr.get(mid), y=mountainArr.get(mid+1);
if(x<y)
{
low=mid+1;
}
else if(x>y)
{
if(temp<x)
{
peak=mid;
temp=x;
}
high=mid-1;
}
}
int a=mountainArr.get(peak);
if(a==target) return peak;
low=0;high=peak-1;
while(low<=high)
{
int mid=low+(high-low)/2;
int x=mountainArr.get(mid);
if(x==target)
return mid;
else if(x>target)
high=mid-1;
else if(x<target)
low=mid+1;
}
low=peak+1; high=n-1;
while(low<=high)
{
int mid=low+(high-low)/2;
int x=mountainArr.get(mid);
if(x==target)
return mid;
else if(x<target)
high=mid-1;
else if(x>target)
low=mid+1;
}
return -1;
}
};