-
Notifications
You must be signed in to change notification settings - Fork 0
/
Top_K_Frequent_In_Array.cpp
55 lines (45 loc) · 1.24 KB
/
Top_K_Frequent_In_Array.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
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
static bool comparator(pair<int,int> a, pair<int,int>b)
{
if(a.second == b.second) return a.first > b.first;
else return a.second > b.second;
}
vector<int> topK(vector<int>& arr, int k) {
vector<int> res;
vector<pair<int, int>> vec;
map<int, int> mpp;
int n = arr.size();
for(auto it : arr)
mpp[it]++;
for(auto it : mpp)
vec.push_back({it.first, it.second});
sort(vec.begin(), vec.end(), comparator);
for(int i = 0; i < vec.size() && i < k; i++)
res.push_back(vec[i].first);
return res;
}
};
//{ Driver Code Starts.
int main() {
int tc;
cin >> tc;
while (tc--) {
int n;
cin >> n;
vector<int> nums(n);
for (auto &i : nums) cin >> i;
int k;
cin >> k;
Solution obj;
vector<int> ans = obj.topK(nums, k);
for (auto i : ans) cout << i << " ";
cout << "\n";
}
return 0;
}
// } Driver Code Ends