-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path12.12.2024.cpp
40 lines (40 loc) · 896 Bytes
/
12.12.2024.cpp
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
class Solution {
public:
int countFreq(vector<int>& arr, int target) {
// code here
int first=-1, last=-1;
int lo=0, hi=arr.size()-1;
while(lo<=hi){
int mid=(lo+hi)/2;
if(arr[mid]==target){
first=mid;
hi=mid-1;
}
else if(arr[mid]<target){
lo=mid+1;
}
else{
hi=mid-1;
}
}
lo=0;
hi=arr.size()-1;
while(lo<=hi){
int mid=(lo+hi)/2;
if(arr[mid]==target){
last=mid;
lo=mid+1;
}
else if(arr[mid]<target){
lo=mid+1;
}
else{
hi=mid-1;
}
}
if(last==-1){
return 0;
}
return last-first+1;
}
};