Need Help in One of the GFG(GEEKS FOR GEEKS) questions (Top K Frequent Elements in Array — I)

Revision en2, by ansh_u_oo7, 2024-01-05 21:35:09

I solved this question using a vector of pairs can someone give me a better approach for this IT WOULD BE OF REALLY GREAT HELP

vector topK(vector& nums, int k) {

map<int,int>mp;
    for(int i=0;i<nums.size();i++)
    {
        mp[nums[i]]++;
    }
    vector<pair<int,int>>p;
    for(auto it:mp)
    {
        p.push_back(make_pair(it.second,it.first));
    }

    sort(p.begin(),p.end());
    reverse(p.begin(),p.end());
    vector<int>v;
   for(int i=0;i<k;i++)
   {
    v.push_back(p[i].second);    
   }
    return v;
}
Tags #dsa #algorithms, #hashing, #pairs, #array #vector

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English ansh_u_oo7 2024-01-05 21:35:09 17 Tiny change: 'ms, int k) {\n // Code here\n ' -> 'ms, int k)\n {\n \n '
en1 English ansh_u_oo7 2024-01-05 21:33:48 765 Initial revision (published)