Advertisement
ostapdontstop

Untitled

Jun 9th, 2023
706
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.61 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<int> topKFrequent(vector<int>& nums, int k) {
  4.         std::unordered_map<int, int> m;
  5.         for(int n : nums) {
  6.             m[n]++;
  7.         }
  8.  
  9.         std::priority_queue<int, std::vector<int>, std::function<bool(int,int)>>
  10.         q([&m](int a, int b){
  11.             return m[a] > m[b];
  12.         });
  13.  
  14.         for(auto& [n,_] : m) {
  15.             q.push(n);
  16.             if (q.size() > k) {
  17.                 q.pop();
  18.             }
  19.         }
  20.         vector<int> res(q.size());
  21.         std::copy(&(q.top()), &(q.top()) + q.size(), &res[0]);
  22.         return res;
  23.     }
  24. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement