-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1095. Find in Mountain Array.cpp
56 lines (53 loc) · 1.43 KB
/
1095. 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
class Solution {
public:
int findInMountainArray(int target, MountainArray &mountainArr)
{
int start = 0;
int end = mountainArr.length()-1;
int mid = start + (end - start)/2;
while(start < end)
{
if(mountainArr.get(mid) < mountainArr.get(mid+1))
start = mid +1;
else
end = mid;
mid = start + (end - start)/2;
}
int peak = mid;
int left = -1, right = -1;
start = 0;
end = peak;
mid = start + (end - start)/2;
while(start <= end)
{
int middle = mountainArr.get(mid);
if(middle == target)
left = mid;
if(middle < target )
start = mid + 1;
else
end = mid - 1;
mid = start + (end - start)/2;
}
start = peak;
end = mountainArr.length()-1;
mid = start + (end - start)/2;
while(start <= end)
{
int middle = mountainArr.get(mid);
if(middle == target)
right = mid;
if(middle > target )
start = mid + 1;
else
end = mid - 1;
mid = start + (end - start)/2;
}
if(left == right)
return left;
else if(left != -1 )
return left;
else
return right;
}
};