Repository navigation
Expand file tree
/
Copy pathSearchRange.java
More file actions
56 lines (42 loc) · 1.44 KB
/
Copy pathSearchRange.java
File metadata and controls
56 lines (42 loc) · 1.44 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
package BinaySearch;
import java.util.Arrays;
public class SearchRange {
public static void main(String[] args) {
int[] array = {5,7,7,8,8,10};
int[] arrayWithAnswers = searchRange(array,6);
System.out.println(Arrays.toString(arrayWithAnswers));
}
static int[] searchRange(int[] nums, int target) {
int[] ans = {-1,-1};
ans[0] = getIndex(nums, target, true);
if (ans[-1] != -1){
ans[1] = getIndex(nums, target, false);
}
return ans;
}
//This function returns the index of the target number
static int getIndex(int[] array, int target, boolean findStartIndex){
int answer = -1;
int startIndex = 0;
int endIndex = array.length -1;
while(startIndex <= endIndex){
//Find Middle Element
int middle = startIndex + (endIndex - startIndex)/2;
if (target < array[middle]){
endIndex = middle-1;
// System.out.println("Start Index Incremented");
}else if(target > array[middle]){
startIndex = middle+1;
// System.out.println("End Index Decremented");
}else{
answer = middle;
if (findStartIndex){
endIndex = middle -1;
}else {
startIndex = middle + 1;
}
}
}
return answer;
}
}