-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFirstLastPositionOfElement.java
51 lines (39 loc) · 1.15 KB
/
FirstLastPositionOfElement.java
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
package com.company;
import java.util.Arrays;
public class FirstLastPositionOfElement {
public static void main(String[] args) {
int[] nums = {5,7,7,8,8,10};
int target = 8;
System.out.println(Arrays.toString(searchRange(nums, target)));
}
static int[] searchRange(int[] nums, int target){
int [] ans = {-1, 1};
int start = search(nums, target, true);
int end = search(nums, target, false);
ans[0] = start;
ans[1] = end;
return ans;
}
static int search( int[] nums, int target, boolean findStartInd){
int ans =-1;
//basic binary search
int start = 0;
int end = nums.length -1;
while(start<= end){
int mid = start + (end - start)/2 ;
if(target > nums[mid]){
start = mid + 1;
} else if(target < nums[mid]){
end = mid - 1;
} else{
ans = mid ;
if(findStartInd){
end = mid - 1;
} else{
start = mid + 1;
}
}
}
return ans;
}
}