-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1095. Find in Mountain Array.java
60 lines (56 loc) · 1.56 KB
/
1095. Find in Mountain Array.java
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
/**
* // 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 mountainArr) {
int peakIdx=findPeak(mountainArr);
int left=findInLeft(mountainArr, 0, peakIdx, target);
int right=findInRight(mountainArr, peakIdx, mountainArr.length()-1, target);
if(left!=-1) return left;
return right;
}
private int findPeak(MountainArray arr) {
int l=0;
int h=arr.length()-1;
while(l+1<h) {
int mid=(l+h)/2;
if(arr.get(mid)<arr.get(mid+1)) {
l=mid;
}else {
h=mid;
}
}
return h;
}
private int findInLeft(MountainArray arr, int start, int end, int target) {
int l=start;
int h=end+1;
while(l+1<h) {
int mid=(l+h)/2;
if(arr.get(mid)<=target) {
l=mid;
}else {
h=mid;
}
}
return arr.get(l) == target ? l : -1 ;
}
private int findInRight(MountainArray arr, int start, int end, int target) {
int l=start-1;
int h=end;
while(l+1<h) {
int mid=(l+h)/2;
if(arr.get(mid)<=target) {
h=mid;
}else {
l=mid;
}
}
return arr.get(h) == target ? h : -1 ;
}
}