Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Logic1:
- use a map and store frequency of each element.make a min heap of k size.
- push elements from map to min heap where first element should be frequency
- and second element as elements that sorting happen on the basis of first element.
- while pushing compare top elememt of min heap with current element of map,if current
- element frequency is greater than top element,remove the top element and push current
- element else continue.
- finally all element of heap is the answer.
- Logic2:
- store the frequency of every elemnt in map.
- make an array of vector of maximum number of frequency.
- for every frequency there is one block,so push the elements in his frequency vector.
- finally,traverse from last of array select first k elements for answer.
- */
- class Solution {
- public:
- vector<int> topKFrequent(vector<int>& nums, int k) {
- unordered_map<int,int>mp;
- int _max=INT_MIN;
- for(auto itr:nums){ mp[itr]++; _max=max(mp[itr],_max); }
- vector<int> arr[_max+1];
- vector<int> ans;
- for(auto itr:mp){
- arr[itr.second].push_back(itr.first);
- }
- int i=_max;
- while(i>=0 && k ){
- for(auto itr:arr[i]){
- ans.push_back(itr);
- if(!--k)break;
- }
- i--;
- }
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement