LeetCode 347. Top K Frequent Elements

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

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

Input: nums = [1], k = 1
Output: [1]

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.

解析:给一个数组,统计每个词语的词频,然后输出出现频率最高的top k个元素。

可以考虑使用一个map统计每个元素出现的次数,然后使用优先队列priority_queue来存放pair对数据。由大到小排序,循环K次输出结果。代码如下:

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        vector<int> result;
        unordered_map<int, int> count_map;
        for(auto num : nums)
        {
            count_map[num] += 1;
        }
        priority_queue<pair<int, int>> que;
        for(auto it = count_map.begin(); it != count_map.end(); it++)
        {
            que.push(pair(it->second, it->first));
        }
        for(int i=0; i < k; i++)
        {
            result.push_back(que.top().second);
            que.pop();
        }
        return result;
    }
};

运行时间:

Add a Comment

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据