Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
- Input format
- First line contains an integer N - Number of elements in the array.
- Second line contains N integers - The array elements.
- Third line contains the integer k.
- Output format
- Print k integers in a single line.
- Sample Input 1
- 7
- 2 8 2 7 4 2 4
- 2
- Sample Output 1
- 2 4
- Explanation
- Frequency of 2: 3
- Frequency of 4: 2
- Frequency of 7: 1
- Frequency of 8: 1
- The two most frequent elements in the given array are 2 and 4.
- Constraints
- 1 <= N <= 10^5
- 1 <= k <= Number of unique elements in the array.
- 0 <= array elements <= 10^5
- */
- vector<int> topKFrequent(vector<int>& nums, int k) {
- priority_queue<pair<int,int>>pq;
- unordered_map<int,int>mp;
- vector<int>res;
- int n=nums.size();
- for(auto ele:nums){
- if(mp.find(ele)==mp.end())
- mp[ele]=1;
- else
- mp[ele]++;
- }
- for(auto it:mp){
- pair<int,int>p={it.second,it.first};
- pq.push(p);
- }
- while(!pq.empty()){
- auto ele=pq.top().second;
- res.push_back(ele);
- if(res.size()==k)
- return res;
- pq.pop();
- }
- return res;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement