-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSorting_Elements_Of_Arrays_By_Fraquency.cpp
63 lines (51 loc) · 1.37 KB
/
Sorting_Elements_Of_Arrays_By_Fraquency.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
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
// Complete this function
// Function to sort the array according to frequency of elements.
vector<int> sortByFreq(vector<int>& arr) {
map<int, int> mpp;
vector<int> ans;
vector<pair<int, int>> k;
for(auto it : arr) mpp[it]++;
for(auto it : mpp) k.push_back({it.second, it.first});
sort(k.begin(), k.end(), [](pair<int, int>& a, pair<int, int>& b)
{
if (a.first == b.first) return a.second < b.second;
return a.first > b.first;
});
for(auto it : k)
{
for(int i = 0; i < it.first; i++)
ans.push_back(it.second);
}
return ans;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
cin.ignore();
while (t--) {
string input;
int num;
vector<int> arr;
getline(cin, input);
stringstream s2(input);
while (s2 >> num) {
arr.push_back(num);
}
Solution obj;
vector<int> v;
v = obj.sortByFreq(arr);
for (int i : v)
cout << i << " ";
cout << endl;
}
return 0;
}
// } Driver Code Ends