forked from PEC-CSS/graveyard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MountainArray.java
60 lines (56 loc) · 1.67 KB
/
MountainArray.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
package dsa;
public class MountainArray {
public static int findInMountainArray(int target, int mountainArr[]) {
int i = -1;
int peak = binSrchPk(mountainArr);
i = binSrch(mountainArr, 0, peak, target, true);
if(i != -1) {
return i;
}
return binSrch(mountainArr, peak, mountainArr.length - 1, target, false);
}
public static int binSrch(int mountainArr[], int l, int r, int target, boolean asc) {
while(l <= r) {
int mid = (l + r)/2;
int midval = mountainArr[mid];
if(midval == target) {
return mid;
}
if(midval <= target) {
if(asc) {
l = mid + 1;
} else {
r = mid - 1;
}
continue;
}
if(asc) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return -1;
}
public static int binSrchPk(int mountainArr[]) {
int l = 0, r = mountainArr.length - 1;
while(l <= r) {
int mid = (l + r)/2;
int midval = mountainArr[mid];
int midvall = mountainArr[mid - 1];
int midvalr = mountainArr[mid + 1];
if(midvall <= midval && midval >= midvalr) {
return mid;
}
if(midvall <= midval && midval <= midvalr) {
l = mid;
continue;
}
r = mid;
}
return -1;
}
public static void main(String[] args) {
System.out.println(findInMountainArray(7, new int[]{1,2,3,4,5,3,1}));
}
}