当前位置:   article > 正文

Leecode347 前k个高频元素

Leecode347 前k个高频元素
  1. class Solution {
  2. public:
  3. static bool compare(pair<int, int>& m, pair<int, int>& n){
  4. return m.second > n.second;
  5. }
  6. vector<int> topKFrequent(vector<int>& nums, int k) {
  7. int n = nums.size();
  8. unordered_map<int, int> record;
  9. for(auto x : nums){
  10. record[x]++;
  11. }
  12. priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(&compare)> pq(compare);
  13. for(auto x : record){
  14. pq.emplace(x);
  15. if(pq.size() > k){
  16. pq.pop();
  17. }
  18. }
  19. vector<int> res;
  20. while(!pq.empty()){
  21. res.push_back(pq.top().first);
  22. pq.pop();
  23. }
  24. return res;
  25. }
  26. };

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/677774
推荐阅读
相关标签
  

闽ICP备14008679号