class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String,Integer> count = new HashMap<>();
for(String word : words){
//统计word出现次数,第一次出现该单词则次数为:(0+1)次,和前面的结果否则累加。
count.put(word,count.getOrDefault(word,0)+1);
}
List<String> candidates = new ArrayList<>(count.keySet());
//注意:sort()默认指定升序排序
candidates.sort((a,b)->{
if(count.get(a).equals(count.get(b))){
//若两者数量相同,就按照字典序排序
return a.compareTo(b);
}else{
//★★★sort()方法是升序排序!!必须: 后-前
return count.get(b)-count.get(a);
}
});
return candidates.subList(0,k);
}
}
leetCode692-前k个高频单词
最新推荐文章于 2024-11-12 21:14:07 发布