题目描述
思路
注意是前K个高频单词,就是TopK问题,只能用小根堆找最大的K个元素啊,用大根堆找的就是最小的K个元素了
思路一:
class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> map = new HashMap<>();
// 小顶堆
PriorityQueue<Map.Entry<String, Integer> > heap = new PriorityQueue<>(
(s1, s2) -> {
if (s1.getValue().equals(s2.getValue())) {
return s2.getKey().compareTo(s1.getKey());
} else {
return s1.getValue() - s2.getValue();
}
}
);
List<String> res = new ArrayList<>();
for (String str : words) {
map.put(str, map.getOrDefault(str, 0) + 1);
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
heap.add(entry);
if (heap.size() > k) {
heap.remove();
}
}
while (!heap.isEmpty()) {
res.add(heap.remove().getKey());
}
Collections.reverse(res);
return res;
}
}
标签:map,res,s1,getValue,单词,heap,s2,LeetCode,LeetCode692
From: https://www.cnblogs.com/keyongkang/p/17908869.html