692. 前K个高频单词

692. 前K个高频单词

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

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

注意:

  1. 假定 k 总为有效值, 1 ≤ k ≤ 集合元素数。
  2. 输入的单词均由小写字母组成。

力扣链接:https://leetcode-cn.com/problems/top-k-frequent-words/

示例 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 次。
class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        Map<String, Integer> map = new HashMap<String, Integer>();
        for (String word : words) {
            map.put(word, map.getOrDefault(word, 0) + 1);
        }
        List<String> res = new ArrayList<String>();
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            res.add(entry.getKey());
        }
        Collections.sort(res, 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 res.subList(0, k);
    }
}
  • map.getOrDefault(Object key, V defaultValue) 当Map集合中有这个key时,就使用这个key对应的value值,如果没有这个key就使用默认值defaultValue;
  • map.entrySet() 由于Map中存放的元素均为键值对,故每一个键值对必然存在一个映射关系。Map中采用Entry内部类来表示一个映射项,映射项包含Key和Value
    Map.Entry里面包含getKey()和getValue()方法。 -- 该方法返回值就是map中各个键值对映射关系的集合。
posted @ 2021-05-22 09:41  Manan_vision  阅读(72)  评论(0)    收藏  举报