knakul853

Untitled

Jun 18th, 2020
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<int> topKFrequent(vector<int>& nums, int k) {
  4.        
  5.         int n = (int)nums.size();
  6.        
  7.         unordered_map<int,int>ump;
  8.         for( int num : nums )ump[num]++;
  9.        
  10.         vector<vector<int>>bucket(n+1);
  11.         vector<int>ans;
  12.        
  13.         for(auto it: ump )
  14.         {
  15.              bucket[it.second].push_back(it.first);
  16.             //cout<<it.second<<"\n";
  17.         }
  18.        
  19.         for(int i=(int)bucket.size()-1;i>=0;i--)
  20.         {
  21.             for(int j=0;j < (int)bucket[i].size(); j++ )
  22.             {
  23.                 ans.push_back(bucket[i][j]);
  24.                 if((int)ans.size() == k) return ans;
  25.             }
  26.         }
  27.        
  28.         return ans;
  29.        
  30.     }
  31. };
  32.  
  33. class Solution {
  34. public:
  35.     vector<int> topKFrequent(vector<int>& nums, int k) {
  36.        
  37.         int n = nums.size();
  38.        
  39.         unordered_map<int,int>ump;
  40.        
  41.         for(int i=0;i<n;i++)
  42.         {
  43.             ump[nums[i]]++;
  44.         }
  45.        
  46.            vector<pair<int,int>>ans(ump.begin(),ump.end());
  47.             sort(ans.begin(),ans.end(),[](pair<int,int>p1,pair<int,int>p2){
  48.             if(p1.second == p2.second)return p1.first > p2.first;
  49.            
  50.                 return p1.second > p2.second;
  51.         });
  52.        
  53.       vector<int>res(k);
  54.         for(int i=0;i<k;i++)
  55.         {
  56.             res[i] = ans[i].first;
  57.         }
  58.         return res;
  59.        
  60.        
  61.        
  62.     }
  63. };
Add Comment
Please, Sign In to add comment