leetcode-347-前K个高频元素

//利用优先队列(注意优先队列的写法,包括创建最小堆还是最大堆,包括写不写自己的比较函数)

//pair比较时只比较第一个元素

class Solution {

public:

    vector<int> topKFrequent(vector<int>& nums, int k) {

        unordered_map<int, int> freq;  //元素,频率

        for (auto i:nums) freq[i]++;

        priority_queue<pair<int, int>, vector<pair<int,int>>, greater<pair<int, int>>> pq; //创建优先队列,维护其中只有K个元素,比较方式为less(最小堆),保持最小的先出队,频率,元素

        for (auto f:freq){

            pq.push(make_pair(f.second, f.first));

            if (pq.size() > k) pq.pop();

        }

        vector<int> res;

        while (!pq.empty()){

            res.push_back(pq.top().second);

            pq.pop();

        }

        return res;

    }

};

相关文章:

  • 2021-08-06
  • 2022-12-23
  • 2022-12-23
  • 2021-09-12
  • 2021-05-18
  • 2021-06-06
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-01
  • 2022-12-23
  • 2022-12-23
  • 2022-03-09
  • 2021-07-06
  • 2021-12-04
  • 2021-10-08
相关资源
相似解决方案