-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathProblem_4_Number_Range.java
More file actions
35 lines (32 loc) · 1.06 KB
/
Problem_4_Number_Range.java
File metadata and controls
35 lines (32 loc) · 1.06 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
package Modified_Binary_Search;
// Problem Statement: Number Range (medium)
// LeetCode Question: 34. Find First and Last Position of Element in Sorted Array
public class Problem_4_Number_Range {
public int[] findRange(int[] arr, int key){
int[] result = new int[] {-1, -1};
result[0] = search(arr, key, false);
if (result[0] != -1) result[1] = search(arr, key, true);
return result;
}
// Modified Binary Search
private static int search (int[] arr, int key, boolean findMaxIndex) {
int keyIndex = -1;
int start = 0, end = arr.length - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (key < arr[mid]) {
end = mid - 1;
} else if (key > arr[mid]) {
start = mid + 1;
} else {
keyIndex = mid;
if (findMaxIndex) {
start = mid + 1;
} else {
end = mid - 1;
}
}
}
return keyIndex;
}
}