forked from MohmedIkram/Hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Find First and Last Position of Element in Sorted Array
71 lines (55 loc) · 1.56 KB
/
Find First and Last Position of Element in Sorted Array
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
class Solution {
public:
int firstOcc(vector<int>& nums,int s,int e, int target,int ans) {
if(s>e)
{
return ans;
}
int mid=s+(e-s)/2;
if(nums[mid]==target)
{
ans=mid;
return firstOcc(nums,s,mid-1,target,ans);
}
if(nums[mid]<target)
{
return firstOcc(nums,mid+1,e,target,ans);
}
else{
return firstOcc(nums,s,mid-1,target,ans);
}
return ans;
}
int lastOcc(vector<int>& nums,int s,int e, int target,int ans) {
// int s=0;
// int e=nums.size();
if(s>e)
{
return ans;
}
int mid=s+(e-s)/2;
if(nums[mid]==target)
{
ans=mid;
return lastOcc(nums,mid+1,e, target,ans);
}
if(nums[mid]<target)
{
return lastOcc(nums,mid+1,e,target,ans);
}
else
return lastOcc(nums,s,mid-1,target,ans);
return ans;
}
vector<int> searchRange(vector<int>& nums, int target) {
int s=0;
int e=nums.size()-1;
int ans=-1;
vector<int>sol;
int first=firstOcc(nums,s,e,target,ans);
int last=lastOcc(nums,s,e,target,ans);
sol.push_back(first);
sol.push_back(last);
return sol;
}
};