-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathFirstAndLastOccuranceOfElement.java
More file actions
48 lines (43 loc) · 1.31 KB
/
FirstAndLastOccuranceOfElement.java
File metadata and controls
48 lines (43 loc) · 1.31 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
class Solution {
public int[] searchRange(int[] nums, int target) {
// define array for storing output
int arr[] = new int[2];
// initialize with -1
Arrays.fill(arr,-1);
// border case
if(nums==null || nums.length==0) return arr;
arr[0] = search(nums,target,true);
arr[1] = search(nums,target,false);
return arr;
}
int search(int nums[],int target, boolean isFirst)
{
// utility variables for binary search
int lo=0,hi=nums.length-1,mid=0;
int index=-1;
while(lo<=hi)
{
mid=lo+(hi-lo)/2;
if(nums[mid]==target)
{
// for first
// if you see a number greater than or equal to target then move towards left
if(isFirst)
{
index=mid;
hi=mid-1;
}
// for second
// if you see a number less than or equal to target then move towards right
else
{
index=mid;
lo=mid+1;
}
}
else if(nums[mid]>target) hi=mid-1;
else lo=mid+1;
}
return index;
}
}