(LeetCode 热题 100) 347. 前 K 个高频元素(哈希表、优先队列)

题目:347. 前 K 个高频元素

在这里插入图片描述

思路:用哈希表来记录每个元素出现的次数,然后使用优先队列即可。时间复杂度优于0(nlogn)。

C++版本:

class Solution {
public:
    typedef pair<int,int> PII;
    vector<int> topKFrequent(vector<int>& nums, int k) {
    	//哈希表记录每个元素出现的次数
        unordered_map<int,int> mp;
        for(auto x:nums){
            mp[x]++;
        }
        //使用优先队列
        priority_queue<PII> qu;
        for(auto &t:mp){
            qu.push({t.second,t.first});
        }
        //前k个高频元素
        vector<int> v;
        int ans=0;
        while(ans<k){
            PII tmp=qu.top();
            qu.pop();
            v.push_back(tmp.second);
            ans++;
        }
        return v;
    }
};

JAVA版本:

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
    	//哈希表记录每个元素出现的次数
        Map<Integer,Integer> mp=new HashMap<Integer,Integer>();
        for(var x:nums){
            mp.put(x,mp.getOrDefault(x,0)+1);
        }
        //使用优先队列
        PriorityQueue<Map.Entry<Integer,Integer>> qu = new PriorityQueue<>((a, b) -> b.getValue() - a.getValue());
        for(var x:mp.entrySet()){
            qu.offer(x);
        }
        //前k个高频元素
        int[] v=new int[k];
        int ans=0;
        while(ans<k){
            v[ans++]=qu.poll().getKey();
        }
        return v;
    }
}

相关知识点:JAVA集合类:List、Queue、Set、Map
java中PriorityQueue的介绍与实现

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值