692. 前K个高频单词

给一非空的单词列表,返回前 k 个出现次数最多的单词。

返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率,按字母顺序排序。

示例 1:

输入: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
输出: ["i", "love"]
解析: "i" 和 "love" 为出现次数最多的两个单词,均为2次。
注意,按字母顺序 "i" 在 "love" 之前。

示例 2:

输入: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
输出: ["the", "is", "sunny", "day"]
解析: "the", "is", "sunny" 和 "day" 是出现次数最多的四个单词,
出现次数依次为 4, 3, 2 和 1 次。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/top-k-frequent-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.*;

class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        if (words == null || words.length == 0) {
            return Collections.emptyList();
        }

        Map<String, Integer> timesMap = new HashMap<>();
        for (String word : words) {
            timesMap.put(word, timesMap.getOrDefault(word, 0) + 1);
        }

        Comparator<String> comparator = new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                Integer time1 = timesMap.get(o1);
                Integer time2 = timesMap.get(o2);
                if (!time1.equals(time2)) {
                    return time1.compareTo(time2);
                } else {
                    return o2.compareTo(o1);
                }
            }
        };

        PriorityQueue<String> queue = new PriorityQueue<>(comparator);

        for (Map.Entry<String, Integer> entry : timesMap.entrySet()) {
            if (queue.size() != k) {
                queue.offer(entry.getKey());
            } else {
                if (comparator.compare(entry.getKey(), queue.peek()) > 0) {
                    queue.poll();
                    queue.offer(entry.getKey());
                }
            }
        }

        String[] ans = new String[queue.size()];

        for (int i = ans.length - 1; i >= 0; --i) {
            ans[i] = queue.poll();
        }

        return Arrays.asList(ans);
    }
}
posted @   Tianyiya  阅读(36)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示