leetcode 347.前k个高频元素

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

示例 1:

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

示例 2:

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

提示:

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

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

//哈希+最大堆
//注意哈希表的遍历
class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        vector<int> res;
        priority_queue<pair<int,int>> heap;
     
        unordered_map<int,int> map;
        unordered_map<int,bool> st;
        for(int i=0;i<nums.size();i++){
            map[nums[i]]++;
            heap.push({map[nums[i]],nums[i]});
   
        }       
        int curr;
        while(k){
            pair<int,int> top=heap.top();
            heap.pop();
            curr=top.second;
            if(!st[curr]){
                st[curr]=true;
                res.push_back(curr);
                k--;
            }
        }

        return res;
    }
};
        // for(auto it = mp.begin(); it != mp.end(); it++) {
        //     pq.push(pair<int, int>(it->second, it->first));
        // }

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值