ansh_u_oo7's blog

By ansh_u_oo7, history, 8 months ago, In English

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;
}
  • Vote: I like it
  • -16
  • Vote: I do not like it

»
8 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by ansh_u_oo7 (previous revision, new revision, compare).

»
8 months ago, # |
  Vote: I like it 0 Vote: I do not like it

after you build the freq map you can use a multiset or heap maintain k elements with highest freq as you iterate over the map