1. 程式人生 > >leetcode 347. Top K Frequent Elements

leetcode 347. Top K Frequent Elements

.html length log push_back .cn ack solution code pair

用優先隊列排序,優先隊列是大根堆

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        vector<int> result;
        int length = nums.size();
        if(length <= 0)
            return result;
        unordered_map<int,int> m;
        priority_queue
<pair<int,int>> n; for(auto a : nums) m[a]++; for(auto a : m) n.push({a.second,a.first}); for(int i = 0;i < k;i++){ result.push_back(n.top().second); n.pop(); } return result; } };

https://www.cnblogs.com/grandyang/p/5454125.html

leetcode 347. Top K Frequent Elements