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; }
Auto comment: topic has been updated by ansh_u_oo7 (previous revision, new revision, compare).
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
got it thnqq