class Solution {
public List<String> topKFrequent(String[] words, int k) {
// 1,定义一个哈希表
HashMap<String,Integer> hashMap = new HashMap<>();
// 2,统计下单次列表中单次出现的频率
for (String str : words) {
// 3,判断哈希表如果没有存这个单词
if(!hashMap.containsKey(str)) {
hashMap.put(str,0);
}
// 4,如果单词已经存在
int count = hashMap.get(str)+1;
hashMap.put(str,count);
}
// 5,定义堆 和排序方式
PriorityQueue<String> minQueue = new PriorityQueue<>(
(w1,w2) ->
hashMap.get(w1).equals(hashMap.get(w2)) ? w2.compareTo(w1) : hashMap.get(w1) - hashMap.get(w2)
);
// 6,添加哈希表中key到堆中
for (String key : hashMap.keySet()) {
minQueue.add(key);
// 7,堆中只能存储k各元素
if (minQueue.size() >k) {
minQueue.poll();
}
}
List<String> list =new ArrayList<>();
while(!minQueue.isEmpty()) {
list.add(minQueue.poll());
}
Collections.reverse(list);
return list;
}
}