前K个高频单词
给一非空的单词列表,返回前 k 个出现次数最多的单词。
返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率,按字母顺序排序。
示例 1:
输入: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
输出: ["i", "love"]
解析: "i" 和 "love" 为出现次数最多的两个单词,均为2次。
注意,按字母顺序 "i" 在 "love" 之前。
思路+代码+注释:
public List<String> topKFrequent(String[] words, int k) {
/*
思路:使用hashMap统计每个单词出现的次数,然后堆排序按照次数从高到低进行排序,次数相同的在按照字母顺序排序
*/
Map<String,Integer> map=new HashMap<>();
for (String s:words
) {
if (map.containsKey(s))
{
map.put(s,map.get(s)+1);
}else {
map.put(s,1);
}
}
PriorityQueue<Map.Entry> priorityQueue=new PriorityQueue<>(new Comparator<Map.Entry>() {
@Override
public int compare(Map.Entry o1, Map.Entry o2) {
Integer n1=(Integer)o1.getValue();
Integer n2=(Integer)o2.getValue();
if (n1.equals(n2))
{
String s1=(String)o1.getKey();
String s2=(String)o2.getKey();
return s1.compareTo(s2);
}else {
return n2-n1;
}
}
});
priorityQueue.addAll(map.entrySet());
List<String> res=new ArrayList<>();
for (int i = 0; i < k; i++) {
res.add((String) priorityQueue.poll().getKey());
}
return res;
}