力扣练习006---前K个高频单词(692)

题目描述:

https://leetcode-cn.com/problems/top-k-frequent-words/submissions/

给一非空的单词列表,返回前 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 次。

题目分析:

1、按照描述,不难想到,先统计每个单词出现的次数,然后存储起来,存储最为方便的是HashMap

2、将单词作为key,出现次数作为value,存入map

3、将map按照value排序,排序实现为:优先看单词出现次数,出现次数相同,按照字母表顺序排序

4、这样熟悉java8 stream特性的代码写起来就非常简单了,直接强行一行代码

Java代码:

看看到底是不是一行代码,哈哈哈

    public List<String> topKFrequent(String[] words, int k) {
        return Arrays.stream(words)
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
            .entrySet()
            .stream()
            .sorted((e1, e2) -> {
                // 按照出现次数排序, 出现次数相同, 按照字母顺序排序
                if (e1.getValue().equals(e2.getValue())) {
                    return e1.getKey().compareTo(e2.getKey());
                } else {
                    return e2.getValue().compareTo(e1.getValue());
                }
            })
            .map(Map.Entry::getKey)
            .limit(k)
            .collect(Collectors.toList());
    }

力扣运行结果:

运行结果不尽如人意。。。。。。

原文地址:https://www.cnblogs.com/sniffs/p/12496417.html