-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindInMountainArray.java
More file actions
50 lines (41 loc) · 1.24 KB
/
findInMountainArray.java
File metadata and controls
50 lines (41 loc) · 1.24 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
/**
* // This is MountainArray's API interface.
* // You should not implement it, or speculate about its implementation
* interface MountainArray {
* public int get(int index) {}
* public int length() {}
* }
*/
class Solution {
public int findInMountainArray(int target, MountainArray arr) {
int n = arr.length();
int l = 0, r = n - 1;
while (l < r) {
int mid = l + (r - l) / 2;
if (arr.get(mid) < arr.get(mid + 1)) {
l = mid + 1;
} else {
r = mid;
}
}
int peak = l;
int res = binarySearch(arr, target, 0, peak, true);
if (res != -1) return res;
return binarySearch(arr, target, peak + 1, n - 1, false);
}
private int binarySearch(MountainArray arr, int target, int l, int r, boolean asc) {
while (l <= r) {
int mid = l + (r - l) / 2;
int val = arr.get(mid);
if (val == target) return mid;
if (asc) {
if (val < target) l = mid + 1;
else r = mid - 1;
} else {
if (val < target) r = mid - 1;
else l = mid + 1;
}
}
return -1;
}
}