-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLc_1095.java
More file actions
81 lines (58 loc) · 1.72 KB
/
Lc_1095.java
File metadata and controls
81 lines (58 loc) · 1.72 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//Lc - 1095. Find in Mountain Array
public class Lc_1095 {
public static void main(String[] args) {
int[] arr = {1, 5, 2};
int size = arr.length-1;
int target = 2;
int peak = findPeak(arr, size);
int result = binarySearch(arr, target, 0, peak, true);
if(result != -1){
System.out.println(result);
}
System.out.println(binarySearch(arr, target, peak, size, false));
}
// calculate peak
static int findPeak(int[] arr, int size){
int start = 0;
int end = size;
while(start < end){
int mid = start + (end - start)/2;
if(arr[mid] > arr[mid + 1]){
//if true you are in the descending part of the array
end = mid;
}
else if(arr[mid] < arr[mid + 1]){
//if true you are in the ascending part
start = mid +1;
}
}
return start;
}
// binarySearch
static int binarySearch(int[] arr, int target, int start, int end, boolean isAscending){
while (start <= end) {
int mid = (start + end) / 2;
int midVal = arr[mid];
if (midVal == target) {
return mid;
}
if (isAscending) {
if (target > midVal) {
start = mid + 1;
}
else {
end = mid - 1;
}
}
else {
if (target > midVal) {
end = mid - 1;
}
else {
start = mid + 1;
}
}
}
return -1;
}
}