目录
https://leetcode.com/problems/top-k-frequent-words/
给定一个单词列表,返回前k个出现频率最高的单词的列表。
一、问题描述
测试用例:
Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output: ["i", "love"]
Explanation: "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
返回的列表中从左到右单词的频率依次递减,出现频率相同的单词则字典序在前面的靠前。
输入的单词均只有小写字母;输入的k合法,满足1<=k<=不同单词的数量。
要求时间O(nlogk),空间O(n)。
二、代码实现
1、堆
class Solution {
//堆
public List<String> topKFrequent2(String[] words, int k) {
Map<String, Integer> map = new HashMap<>();
for (int i=0; i<words.length; i++) {
if (map.containsKey(words[i]))
map.put(words[i], map.get(words[i])+1);
else
map.put(words[i], 1);
}
//这里用a.getValue()==b.getValue()可能不太对,==只能在整数为-128-127之间才可以使用,应该使用a.getValue().equals(b.getValue())
//这里用b.getKey().compareTo(a.getKey())是为了让字典序越靠后的单词处在小顶堆的更高处,比如,"abc","abd","bun",小顶堆中的删除顺序应该为"bob","bun","ban".
//这里用a.getValue()-b.getValue()是为了定义优先队列为小顶堆,频率越小的单词处在堆的更高处
PriorityQueue<Map.Entry<String, Integer>> heap = new PriorityQueue<>(
(a,b) -> a.getValue()==b.getValue() ? b.getKey().compareTo(a.getKey()) : a.getValue()-b.getValue()
);
/*
PriorityQueue