【算法训练】LeetCode#692 前K个高频单词

一、描述

692. 前K个高频单词

给定一个单词列表 words 和一个整数 k ,返回前 k 个出现次数最多的单词。

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

示例 1:

输入: words = ["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 次。

二、思路

遍历得到每个单词出现顺序,再根据出现次数排序,次数相同则按字典序排。

三、解题


public class LeetCode692 {

    public class Info{
        String key;
        int nums;

        public Info(){

        }
        public Info(String k,int n){
            key = k;
            nums = n;
        }
    }

    public List<String> topKFrequent(String[] words, int k){
        PriorityQueue<Info> queue = new PriorityQueue<>(new Comparator<Info>() {
            @Override
            public int compare(Info o1, Info o2) {
                if (o1.nums == o2.nums){
                    // 次数相同则字典序
                    return o1.key.compareTo(o2.key);
                }
                return o2.nums - o1.nums;
            }
        });

        HashMap<String,Integer> map = new HashMap<>();
        for (String word : words){
            map.put(word,map.getOrDefault(word,0)+1);
        }
        for (Map.Entry<String,Integer> entry : map.entrySet()){
            queue.add(new Info(entry.getKey(),entry.getValue()));
        }
        List<String> ans = new LinkedList<>();
        while (k > 0){
            ans.add(queue.poll().key);
            k--;
        }
        return ans;
    }
}

posted @ 2023-02-26 16:36  小拳头呀  阅读(20)  评论(0编辑  收藏  举报