leetcode-692-前K个高频单词

Posted caoshikui

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-692-前K个高频单词相关的知识,希望对你有一定的参考价值。

leetcode-692-前K个高频单词

描述

692

思路

  1. 使用hashmap记录 单词 与 对应的出现次数hashmap<String, int>
  2. 将map中的键放入列表list中排序
  3. 排序规则:
    1. 如果出现次数相同,则直接使用字符转的排序规则
    2. 如果出现次数不同, 则按照次数从大到小排序

代码

class Solution{
    public List<String, Integer> topKFrequent(String[] words, int k){
        Map<String, Integer> map = new HashMap<>();
        for(String word : words){
            map.put(word, map.getOrDefault(word, 0) + 1);
        }
        
        List<String> keys = new ArrayList<>();
        for(Map.Entry<String, Integer> entry : map.entrySet()){
            keys.add(entry.getKey());
        }
        
        Collections.sort(keys, new Comparator<String>(){
            public int compare(String word1, String word2){
                return map.get(word1) == map.get(word2) ? word1.compareTo(word2): map.get(word2) - map.get(word1);
            }
        });
        
        return keys.subList(0, k);
    }
}

以上是关于leetcode-692-前K个高频单词的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode:692. 前K个高频单词

leetcode692. 前K个高频单词

leetcode 692. 前K个高频单词

topK问题 前K个高频元素 leetcode692

topK问题 前K个高频元素 leetcode692

LeetCode 692 前K个高频单词[自定义排序 Map] HERODING的LeetCode之路