【优先队列】LeetCode 692. 前K个高频单词
题目链接
思路
还是与前k大问题一样,只不过需要注意一下字典序的问题。
代码
class Solution{
public List<String> topKFrequent(String[] words, int k){
HashMap<String, Integer> wordMap = new HashMap<>();
PriorityQueue<Map.Entry<String, Integer>> wordQueue = new PriorityQueue<>(
new Comparator<Map.Entry<String, Integer>>(){
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2){
if(!o1.getValue().equals(o2.getValue())){
return o1.getValue().compareTo(o2.getValue());
}
return o2.getKey().compareTo(o1.getKey());
}
}
);
List<String> res = new ArrayList<>();
for(String string : words){
wordMap.put(string, wordMap.getOrDefault(string, 0) + 1);
}
for(Map.Entry<String, Integer> entry : wordMap.entrySet()){
wordQueue.add(entry);
if(wordQueue.size() > k){
wordQueue.poll();
}
}
for(int i = 0; i < k; i++){
res.add(wordQueue.poll().getKey());
}
Collections.reverse(res);
return res;
}
}