Given an array of strings words and an integer k, return the k most frequent strings.
Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.
Example 1:
Input: words = [“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.
Example 2:
Input: words = [“the”,“day”,“is”,“sunny”,“the”,“the”,“the”,“sunny”,“is”,“is”], k = 4
Output: [“the”,“is”,“sunny”,“day”]
Explanation: “the”, “is”, “sunny” and “day” are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.
统计words数组中各单词出现的频率,返回频率由高到低的前K个单词。
频率一样时,按字典顺序排序。
首先要统计每个单词出现的频率,所以要用到hash map.
遍历一遍words,保存每个单词和对应的频率到hash map.
然后要按频率由高到低排序,找到对应的单词。
这步可以用优先队列,定义排序规则:按频率由高到低,频率相同时,按字典顺序排序。
最后只需要从优先队列中取出前k个单词装入list。
可以自定义一个class,包含单词和对应的频率
字典顺序的比较可以用String的compareTo方法。
public List<String> topKFrequent(String[] words, int k) {
Queue<Node> heap = new PriorityQueue<>(k, (a, b)->(a.freq == b.freq ?
a.word.compareTo(b.word) : b.freq - a.freq));
HashMap<String, Integer> map = new HashMap<>();
List<String> res = new ArrayList<>();
for(String word : words) {
map.put(word, map.getOrDefault(word, 0)+1);
}
map.forEach((key, val) -> {
heap.offer(new Node(key, val));
});
while(k > 0) {
res.add(heap.poll().word);
k --;
}
return res;
}
class Node{
String word;
int freq;
public Node(String word, int freq) {
this.word = word;
this.freq = freq;
}
}
不过自定义的class没有map中的entrySet高效
public List<String> topKFrequent(String[] words, int k) {
Queue<Map.Entry<String,Integer>> heap = new PriorityQueue<>((a, b)->(a.getValue() == b.getValue() ?
a.getKey().compareTo(b.getKey()) : b.getValue() - a.getValue()));
HashMap<String, Integer> map = new HashMap<>();
List<String> res = new ArrayList<>();
final int num = k;
for(String word : words) {
map.put(word, map.getOrDefault(word, 0)+1);
}
for(Map.Entry<String, Integer> entry : map.entrySet()) {
heap.offer(entry);
}
while(k > 0) {
res.add(heap.poll().getKey());
k --;
}
return res;
}