Advertisement
imashutosh51

Top K frequent elements

Oct 18th, 2022
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. /*
  2. Logic1:
  3. use a map and store frequency of each element.make a min heap of k size.
  4. push elements from map to min heap where first element should be frequency
  5. and second element as elements that sorting happen on the basis of first element.
  6. while pushing compare top elememt of min heap with current element of map,if current
  7. element frequency is greater than top element,remove the top element and push current
  8. element else continue.
  9. finally all element of heap is the answer.
  10.  
  11. Logic2:
  12. store the frequency of every elemnt in map.
  13. make an array of vector of maximum number of frequency.
  14. for every frequency there is one block,so push the elements in his frequency vector.
  15. finally,traverse from last of array select first k elements for answer.
  16. */
  17.  
  18. class Solution {
  19. public:
  20.     vector<int> topKFrequent(vector<int>& nums, int k) {
  21.         unordered_map<int,int>mp;
  22.         int _max=INT_MIN;
  23.         for(auto itr:nums){ mp[itr]++; _max=max(mp[itr],_max); }
  24.         vector<int> arr[_max+1];
  25.         vector<int> ans;
  26.         for(auto itr:mp){
  27.             arr[itr.second].push_back(itr.first);
  28.         }
  29.         int i=_max;
  30.         while(i>=0 && k ){
  31.                 for(auto itr:arr[i]){
  32.                     ans.push_back(itr);
  33.                     if(!--k)break;
  34.                 }
  35.             i--;
  36.         }
  37.         return ans;
  38.     }
  39. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement