-
Notifications
You must be signed in to change notification settings - Fork 1
/
65-find-in-mountain-array.cpp
70 lines (62 loc) · 1.63 KB
/
65-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
65
66
67
68
69
70
/**
* // 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 &mArr)
{
int left = 1, right = mArr.length() - 1;
int peak = -1;
while(left <= right)
{
int mid = (left + right) / 2;
int idx = mArr.get(mid);
int idxL = mArr.get(mid - 1);
int idxR = mArr.get(mid + 1);
if(idx > idxL && idx > idxR)
{
peak = mid;
break;
}
else if(idxR > idx && idx > idxL)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
left = 0, right = peak;
while(left <= right)
{
int mid = (left + right) / 2;
int x = mArr.get(mid);
if(x == target)
return mid;
else if(x < target)
left = mid + 1;
else
right = mid - 1;
}
left = peak, right = mArr.length() - 1;
while(left <= right)
{
int mid = (left + right) / 2;
int x = mArr.get(mid);
if(x == target)
return mid;
else if(x < target)
right = mid - 1;
else
left = mid + 1;
}
return -1;
}
};