Repository navigation
Expand file tree
/
Copy pathFindInMountainArray.java
More file actions
77 lines (59 loc) · 2.24 KB
/
Copy pathFindInMountainArray.java
File metadata and controls
77 lines (59 loc) · 2.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
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
package BinaySearch;
public class FindInMountainArray {
public static void main(String[] args) {
}
static int findInMountainArray(int[] array, int target){
int peakIndex = peakIndexInMountainArray(array);
int firstTry = orderAgnosticBinarySearch(array, target, 0,peakIndex);
if (firstTry != -1){
return firstTry;
}
return orderAgnosticBinarySearch(array,target,peakIndex, array.length -1);
}
static int peakIndexInMountainArray(int[] nums) {
int startIndex = 0;
int endIndex = nums.length -1;
while (startIndex < endIndex){
int middle = startIndex + (endIndex - startIndex)/2;
if (nums[middle] > nums[middle+1]){
//You are in the Descending Part of the Array
//This may be the answer but look at Left of the Array
//This is why end!= mid -1;
endIndex = middle;
}else {
//You are in the Ascending part of the Array
startIndex = middle +1;
}
}
return startIndex;
}
static int orderAgnosticBinarySearch(int[] array, int target, int startIndex, int endIndex){
//Find whether the Array is sorted in Ascending or Descending
boolean isAscending = array[startIndex] < array[endIndex];
while(startIndex <= endIndex){
//Find Middle Element
int middle = (startIndex+endIndex)/2;
if (target == array[middle]){
return middle;
}
if (isAscending){
if (target > array[middle]){
startIndex = middle+1;
System.out.println("Start Index Incremented");
}else{
endIndex = middle-1;
System.out.println("End Index Decremented");
}
}else {
if (target < array[middle]){
startIndex = middle+1;
System.out.println("Start Index Incremented");
}else{
endIndex = middle-1;
System.out.println("End Index Decremented");
}
}
}
return -1;
}
}