LeetCode题解347. Top K Frequent Elements

题目:

Given a non-empty array of integers, return the k most frequent elements.

For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].

Note: 

  • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.


思路:hashmap 和priority_queue

代码:

class Solution {
public:
    //347. Top K Frequent Elements
    //HashMap 和 priority_queue 
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> Map;
        priority_queue<pair<int,int>> PriQ;
        vector<int> res;
        for(auto num : nums) Map[num]++;
        for(auto it : Map) PriQ.push({it.second, it.first});
        for(int i = 0; i < k; i++){
            res.push_back(PriQ.top().second);
            PriQ.pop();
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/u014694994/article/details/80608582