-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumber_Of_Occurence.cpp
87 lines (80 loc) · 1.71 KB
/
Number_Of_Occurence.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
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//{ Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution{
public:
/* if x is present in arr[] then returns the count
of occurrences of x, otherwise returns 0. */
int count(int arr[], int n, int x) {
int first = -1;
int last = -1;
int low = 0;
int high = n - 1;
while(low <= high)
{
int mid = (low + high) / 2;
if(arr[mid] <= x)
{
if(arr[mid] == x) last = mid;
low = mid +1;
}
else
{
high = mid -1;
}
}
low = 0;
high = n;
while(low <= high)
{
int mid = (low + high) / 2;
if(arr[mid] < x)
{
low = mid +1;
}
else
{
if(arr[mid] == x)
{
first = mid;
}
high = mid -1;
}
}
int ans;
if (last == -1 && first == -1)
return 0;
else if (last != -1 && first != -1) ans = last - first +1;
else if (last == -1 && first != -1)
{
last = 0;
ans = last - first +1;
}
else
{
first = 0;
ans = first - last +1;
}
return ans;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int n, x;
cin >> n >> x;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
Solution ob;
auto ans = ob.count(arr, n, x);
cout << ans << "\n";
}
return 0;
}
// } Driver Code Ends