Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
583 B
1
Indexable
Never
class Solution {
public:
    vector<int> topKFrequent(vector<int>& arr, int k) { //bucket
        
        unordered_map<int,int>freq;
        for(auto i:arr) freq[i]++; //get freq of all elements in array

        vector<vector<int>>bucket(arr.size()+1);
        for(auto x:freq){
            bucket[x.second].push_back(x.first); //in bucket map freq with no of elements with that freq
        }

        vector<int>res;
        for(int i=bucket.size()-1;res.size()<k;i--){
            for(auto j:bucket[i]) res.push_back(j);
        }
        return res;
    }
};