-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchRange.java
More file actions
70 lines (52 loc) · 1.74 KB
/
Copy pathSearchRange.java
File metadata and controls
70 lines (52 loc) · 1.74 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
package LeetcodePractice;
public class SearchRange {
public static int[] searchRange(int[] nums, int target) {
int[] result = new int[]{-1, -1};
result[0] = findStartingIndex(nums, target);
result[1] = findEndingIndex(nums, target);
return result;
}
private static int findStartingIndex(int[] nums, int target) {
int left = 0, right = nums.length - 1;
int start = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] >= target) {
if (nums[mid] == target) {
start = mid;
}
right = mid - 1;
} else {
left = mid + 1;
}
}
return start;
}
private static int findEndingIndex(int[] nums, int target) {
int left = 0, right = nums.length - 1;
int end = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] <= target) {
if (nums[mid] == target) {
end = mid;
}
left = mid + 1;
} else {
right = mid - 1;
}
}
return end;
}
public static void main(String[] args) {
int[] nums1 = {5,7,7,8,8,10};
int target1 = 8;
System.out.println(java.util.Arrays.toString(searchRange(nums1, target1)));
int[] nums2 = {5,7,7,8,8,10};
int target2 = 6;
System.out.println(java.util.Arrays.toString(searchRange(nums2, target2)));
int[] nums3 = {};
int target3 = 0;
System.out.println(java.util.Arrays.toString(searchRange(nums3, target3)));
}
}