-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathTop_k_Frequent_Numbers_InAnArray.cpp
58 lines (46 loc) · 1.26 KB
/
Top_k_Frequent_Numbers_InAnArray.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
// C++ Program to print Top k Frequent Numbers in a given Array
#include <bits/stdc++.h>
using namespace std;
void Top_K_FrequentNumbers(int arr[], int n, int k)
{
priority_queue <pair<int,int>, vector<pair<int,int>>, greater< pair<int,int>> > minh;
unordered_map<int,int> mp;
for(int i=0; i<n; i++)
{
mp[arr[i]]++;
}
for(auto i=mp.begin(); i!=mp.end(); i++)
{
minh.push({i->second, i->first});
if(minh.size()>k)
{
minh.pop();
}
}
while(minh.size()>0)
{
cout<<minh.top().second<<" ";
minh.pop();
}
}
int main()
{
int n;
cout<<"Enter the size of Array"<<endl;
cin>>n;
int k;
cin>>k;
int arr[n];
cout<<"Enter the elements of the Array"<<endl;
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
Top_K_FrequentNumbers(arr,n,k);
return 0;
}
/* Time Complexity: O(K logd + d logd)
[ To remove the top of the priority queue O(log d) time is required, so if k elements are removed then O(k log d) time is required, and
To construct a priority queue with d elements, O(d logd) time is required]
Space Complexity: O(d), where d is the count of distinct elements in the array.
*/