-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFinFirstandLastPositionofElementinSortedArray.java
More file actions
87 lines (69 loc) · 1.89 KB
/
FinFirstandLastPositionofElementinSortedArray.java
File metadata and controls
87 lines (69 loc) · 1.89 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
78
79
80
81
82
83
84
85
86
87
package leetcode;
public class FinFirstandLastPositionofElementinSortedArray {
public static void main(String[] args) {
int[] arr = {5,7,7,8,8,10};
System.out.println(searchRange(arr,8)[0]);
System.out.println(searchRange(arr,8)[1]);
}
/**
*
*
*
* Input: nums = [5,7,7,8,8,10], target = 6
* Output: [-1,-1]
*
*
* Input: nums = [5,7,7,8,8,10], target = 8
* Output: [3,4]
*
*
* @param nums
* @param target
* @return
*/
public static int[] searchRange(int[] nums, int target) {
int[] result = new int[2];
result[0] = -1;
result[1] = -1;
if (nums == null || nums.length<1){
return result;
}
result[1] = findRightMostIndex(nums, target);
result[0] = findLeftMostIndex(nums,target);
return result;
}
private static int findRightMostIndex(int[] arr, int target){
int start = 0;
int end = arr.length -1;
int indx = -1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (arr[mid] <= target) {
start = mid;
} else {
end = mid;
}
if (arr[start] == target) {
indx = start;
}
}
return indx;
}
private static int findLeftMostIndex(int[] arr, int target){
int indx = -1;
int end = arr.length - 1;
int start = 0;
while (start + 1 < end){
int mid = start + (end - start)/2;
if (arr[mid] >= target){
end= mid;
}else {
start = mid;
}
}
if (arr[end] == target){
indx = end;
}
return indx;
}
}