Advertisement
vaibhav1906

Top K Frequent Elements

Jan 11th, 2022
1,322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.64 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<int> topKFrequent(vector<int>& nums, int k) {
  4.        
  5.         unordered_map<int,int>mp; //To make the frequency table
  6.         int n = nums.size();
  7.        
  8.         for(int i =0; i<n; i++){
  9.             mp[nums[i]]++;
  10.         }
  11.        
  12.         priority_queue<pair<int,int>> pq;
  13.        
  14.         for(auto it = mp.begin(); it!=mp.end(); it++){
  15.             pq.push({it->second, it->first});
  16.         }
  17.        
  18.         vector<int> ans;
  19.        
  20.         while(k!=0){
  21.             ans.push_back(pq.top().second);
  22.             pq.pop();
  23.             k--;
  24.         }
  25.        
  26.         return ans;
  27.     }
  28. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement