题目描述:给定一个字符串数组,返回出现频率最高的k个字符串
思路:先使用map对词频进行统计,再根据map中的value(字符串出现次数)进行降序排序,可以使用优先队列,自定义比较规则
代码
private static List<String> topK(String[] strings, int k) {
List<String> res = new ArrayList<>();
Map<String, Integer> counts = new HashMap<>();
for (int i = 0; i < strings.length; i++) {
counts.put(strings[i], counts.getOrDefault(strings[i], 0) + 1);
}
PriorityQueue<Map.Entry<String, Integer>> qt = new PriorityQueue<>((e1, e2) -> {
if(e1.getValue().compareTo(e2.getValue()) == 0) {
return e1.getKey().compareTo(e2.getKey());
}
return 0 - e1.getValue().compareTo(e2.getValue());
});
qt.addAll(counts.entrySet());
while (k-- > 0) {
res.add(qt.poll().getKey());
}
return res;
}