-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindFirstAndLastPositionOfElementInSortedArray.java
More file actions
42 lines (39 loc) · 1.27 KB
/
FindFirstAndLastPositionOfElementInSortedArray.java
File metadata and controls
42 lines (39 loc) · 1.27 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
import java.util.Arrays;
/*
* https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
*/
public class FindFirstAndLastPositionOfElementInSortedArray {
public int[] searchRange(int[] nums, int target) {
if (nums.length == 0) {
return new int[]{-1, -1};
}
int anyIndex = Arrays.binarySearch(nums, target);
if (anyIndex < 0) {
return new int[]{-1, -1};
}
return expandRange(nums, target, anyIndex);
}
private int[] expandRange(int[] nums, int target, int anyIndex) {
int[] ans = new int[]{anyIndex, anyIndex};
int firstIndex = anyIndex - 1;
while (firstIndex != -1) {
if (nums[firstIndex] != target) {
break;
}
ans[0]--;
firstIndex--;
}
int lastIndex = anyIndex + 1;
while (lastIndex != nums.length) {
if (nums[lastIndex] != target) {
break;
}
ans[1]++;
lastIndex++;
}
return ans;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(new FindFirstAndLastPositionOfElementInSortedArray().searchRange(new int[]{5, 7, 7, 8, 8, 10}, 8))); // 3.4
}
}