跳转至

347. 前 K 个高频元素

力扣链接(中等):https://leetcode.cn/problems/top-k-frequent-elements

给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。

示例 1:

Text Only
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]

示例 2:

Text Only
输入: nums = [1], k = 1
输出: [1]

提示:

  • 1 <= nums.length <= 105
  • k 的取值范围是 [1, 数组中不相同的元素的个数]
  • 题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的

进阶:你所设计算法的时间复杂度 必须 优于 O(n log n) ,其中 n 是数组大小。

个人题解

时间复杂度:\(O(nlogk)\)

空间复杂度:\(O(n)\)

C++
class Solution {
public:
    class myComp{
        public:
            bool operator()(const pair<int, int>& l, const pair<int, int>& r) {
                // < 即为大根堆(priority_queue第三个模板参数的缺省值就是less),反之
                return l.second > r.second;
            }
    };
    vector<int> topKFrequent(vector<int>& nums, int k) {
        // 使用哈希统计频率 O(n)
        unordered_map<int, int> map;
        for(int i = 0; i < nums.size(); i++) {
            map[nums[i]]++;
        }

        // 排序,定义一个大小为k的小根堆
        // 所谓的priority_queue优先队列其实默认底层实现逻辑就是大根堆
        // <_Tp, _Container = vector<_Tp>, _Compare = less<_Container::value_type>> 
        priority_queue<pair<int, int>, vector<pair<int, int>>, myComp> pri_que;

        // 遍历所有频率O(n) * O(logk)
        // unordered_map<int, int>::iterator it = map.begin()
        for(unordered_map<int, int>::iterator it = map.begin(); it != map.end(); it++) {
            // 操作堆 O(logk)
            pri_que.push(*it);
            // 如果队列中已经大于需要的k个结果,则弹出最小值 O(logk)
            if(pri_que.size() > k) pri_que.pop();
        }

        // 导出前k个高频元素,由于是小根堆,所以需要逆序 O(k)
        vector<int> res;
        for(int i = k - 1; i >= 0; i--) {
            res.push_back(pri_que.top().first);
            pri_que.pop();
        }
        return res;
    }
};