Advertisement
satishfrontenddev5

Untitled

Jan 6th, 2024
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.26 KB | None | 0 0
  1. /*
  2. Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
  3.  
  4. Input format
  5. First line contains an integer N - Number of elements in the array.
  6.  
  7. Second line contains N integers - The array elements.
  8.  
  9. Third line contains the integer k.
  10.  
  11. Output format
  12. Print k integers in a single line.
  13.  
  14. Sample Input 1
  15. 7
  16.  
  17. 2 8 2 7 4 2 4
  18.  
  19. 2
  20.  
  21. Sample Output 1
  22. 2 4
  23.  
  24. Explanation
  25. Frequency of 2: 3
  26.  
  27. Frequency of 4: 2
  28.  
  29. Frequency of 7: 1
  30.  
  31. Frequency of 8: 1
  32.  
  33. The two most frequent elements in the given array are 2 and 4.
  34.  
  35. Constraints
  36. 1 <= N <= 10^5
  37.  
  38. 1 <= k <= Number of unique elements in the array.
  39.  
  40. 0 <= array elements <= 10^5
  41. */
  42.  
  43. vector<int> topKFrequent(vector<int>& nums, int k) {
  44.     priority_queue<pair<int,int>>pq;
  45.     unordered_map<int,int>mp;
  46.     vector<int>res;
  47.     int n=nums.size();
  48.     for(auto ele:nums){
  49.         if(mp.find(ele)==mp.end())
  50.          mp[ele]=1;
  51.          else
  52.           mp[ele]++;
  53.     }
  54.     for(auto it:mp){
  55.         pair<int,int>p={it.second,it.first};
  56.         pq.push(p);
  57.     }
  58.    
  59.  
  60.     while(!pq.empty()){
  61.         auto ele=pq.top().second;
  62.         res.push_back(ele);
  63.         if(res.size()==k)
  64.         return res;
  65.         pq.pop();
  66.     }
  67.     return res;
  68.  
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement