-
Notifications
You must be signed in to change notification settings - Fork 54
/
First and last position in an array
51 lines (51 loc) · 1.39 KB
/
First and last position in an 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
class Solution {
int searchfirst(vector<int> &arr,int size,int key){
int start=0;
int end=size-1;
int target=key;
int mid=start+((end-start)/2);
int ans=-1;
while(start<=end){
if(target==arr[mid]){
ans=mid;
end=mid-1;
}
else if(target<arr[mid]){
end=mid-1;
}
else if(target>arr[mid]){
start=mid+1;
}
mid=start+((end-start)/2);
}
return ans;
}
int searchlast(vector<int> &arr,int size,int key){
int start=0;
int end=size-1;
int target=key;
int mid=start+((end-start)/2);
int ans=-1;
while(start<=end){
if(target==arr[mid]){
ans=mid;
start=mid+1;
}
else if(target<arr[mid]){
end=mid-1;
}
else if(target>arr[mid]){
start=mid+1;
}
mid=start+((end-start)/2);
}
return ans;
}
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ans;
ans.push_back(searchfirst(nums,nums.size(),target));
ans.push_back(searchlast(nums,nums.size(),target));
return ans;
}
};