LeetCode|LeetCode 692. 前K个高频单词

1、题目
【LeetCode|LeetCode 692. 前K个高频单词】前K个高频单词 - 力扣(LeetCode) https://leetcode-cn.com/problems/top-k-frequent-words/
2、题解
本题首先就是需要统计相同单词的个数,使用单词的值来作为HashMap的K,每计数一次就加一。之后我们需要写一个优先队列来设置排序的规则。在比较器中将单词先按单词长度,再按字母升序的顺序进行排序。然后将hashMap中的字符串添加到优先队列之中,如果超过我们所要的字符串数量,就调用poll()移除队首元素.【因为Java的优先队列是二叉树小顶堆,所以队首元素就是最小的那个。比较大小的规则由比较器决定。】最后再将优先队列中的单词添加到result集合中,反转result即可。【因为我们在长度部分是升序排列,所以需要反转一下。】
3、代码

class Solution { public List topKFrequent(String[] words, int k) { //数个数 HashMap contentMap = new HashMap<>(); for (String word:words) {contentMap.put(word,contentMap.getOrDefault(word,0)+1); } //新建对象的时候可以指定一个初始容量,其容量会自动增加。 PriorityQueue priorityQueue = new PriorityQueue<>(k, new Comparator() { @Override public int compare(String o1, String o2) { //升序前减后,降序后减前,这里选择升序。 //o1.compareTo(o2)会返回一个int值,如果0说明o1和o2相等,如果返回负值,那么o1和o2会倒序排序,返回正值,那么o1和o2会正序排序。 return contentMap.get(o1).equals(contentMap.get(o2))?o2.compareTo(o1):contentMap.get(o1)-contentMap.get(o2); } }); for (String word:contentMap.keySet()) { priorityQueue.offer(word); if(priorityQueue.size()>k){ priorityQueue.poll(); } } ArrayList result = new ArrayList<>(); while (!priorityQueue.isEmpty()){ result.add(priorityQueue.poll()); } //反转 Collections.reverse(result); return result; } }

4、执行结果
LeetCode|LeetCode 692. 前K个高频单词
文章图片
image.png

    推荐阅读