Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.2 kB
7
Indexable
#include <bits/stdc++.h>
using namespace std;

    static bool cmp(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> frequencySort(vector<int>& nums) {
        if(nums.size()==1) {
            return nums;
        }
        
        map<int,int> mp;
        
        for(int i=0; i<nums.size(); i++) {
            mp[nums[i]]++;
        }
        
        vector<pair<int,int>> freq;
        
        for(auto m : mp) {
            freq.push_back(m);
        }
        
        sort(freq.begin(), freq.end(), cmp);
        
        vector<int> ans;
        
        for(auto v : freq) 
            for(int i=0; i<v.second; i++) 
                ans.push_back(v.first);
            
        return ans;
    }

int main()
{
    vector<int> nums;
    int n;
    cin>>n;

    for(int i=0; i<n; i++) {
        int x;
        cin>>x;
        nums.push_back(x);
    }
    vector<int> ans = frequencySort(nums);

    for(int i=0; i<ans.size(); i++) {
        cout<<ans[i]<<" ";
    }
    cout<<endl;
return 0;
}