每日一道Leetcode - 692. 前K个高频单词【大顶堆】

本文对比了Python和Java两种编程语言中如何利用Counter和PriorityQueue数据结构,实现查找给定字符串列表中出现频率最高的k个单词。通过实例展示了堆的使用技巧和频率统计在实际问题中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
python实现:

class Solution:
    def topKFrequent(self, words: List[str], k: int) -> List[str]:
        frequency = collections.Counter(words)
        # 大顶堆:最小的在下面,最大的在上面,弹出k个
        queue = [(-freq, word)for word,freq in frequency.items()]
        heapq.heapify(queue)
        return [heapq.heappop(queue)[1] for _ in range(k)]

Java实现:

class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        Map<String,Integer> count = new HashMap();
        for(String word:words){
            count.put(word,count.getOrDefault(word,0)+1);
        }
        PriorityQueue<String> heap = new PriorityQueue<String>(
            (w1,w2) -> count.get(w1).equals(count.get(w2))? w2.compareTo(w1):count.get(w1)
-count.get(w2)        );

        for(String word:count.keySet()){
            heap.offer(word);
            if(heap.size()>k) heap.poll();
        }

        List<String> ans = new ArrayList();
        while (!heap.isEmpty()) ans.add(heap.poll());
        Collections.reverse(ans);
        return ans;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值