Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- vector<int> topKFrequent(vector<int>& nums, int k) {
- int n = (int)nums.size();
- unordered_map<int,int>ump;
- for( int num : nums )ump[num]++;
- vector<vector<int>>bucket(n+1);
- vector<int>ans;
- for(auto it: ump )
- {
- bucket[it.second].push_back(it.first);
- //cout<<it.second<<"\n";
- }
- for(int i=(int)bucket.size()-1;i>=0;i--)
- {
- for(int j=0;j < (int)bucket[i].size(); j++ )
- {
- ans.push_back(bucket[i][j]);
- if((int)ans.size() == k) return ans;
- }
- }
- return ans;
- }
- };
- class Solution {
- public:
- vector<int> topKFrequent(vector<int>& nums, int k) {
- int n = nums.size();
- unordered_map<int,int>ump;
- for(int i=0;i<n;i++)
- {
- ump[nums[i]]++;
- }
- vector<pair<int,int>>ans(ump.begin(),ump.end());
- sort(ans.begin(),ans.end(),[](pair<int,int>p1,pair<int,int>p2){
- if(p1.second == p2.second)return p1.first > p2.first;
- return p1.second > p2.second;
- });
- vector<int>res(k);
- for(int i=0;i<k;i++)
- {
- res[i] = ans[i].first;
- }
- return res;
- }
- };
Add Comment
Please, Sign In to add comment