当前位置:网站首页>LeetCode_优先级队列_692.前K个高频单词
LeetCode_优先级队列_692.前K个高频单词
2022-08-10 23:57:00 【小城老街】
1.题目
给定一个单词列表 words 和一个整数 k ,返回前 k 个出现次数最多的单词。
返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率, 按字典顺序排序。
示例 1:
输入: words = [“i”, “love”, “leetcode”, “i”, “love”, “coding”], k = 2
输出: [“i”, “love”]
解析: “i” 和 “love” 为出现次数最多的两个单词,均为2次。注意,按字母顺序 “i” 在 “love” 之前。
示例 2:
输入: [“the”, “day”, “is”, “sunny”, “the”, “the”, “the”, “sunny”, “is”, “is”], k = 4
输出: [“the”, “is”, “sunny”, “day”]
解析: “the”, “is”, “sunny” 和 “day” 是出现次数最多的四个单词,出现次数依次为 4, 3, 2 和 1 次。
注意:
1 <= words.length <= 500
1 <= words[i] <= 10
words[i] 由小写英文字母组成。
k 的取值范围是 [1, 不同 words[i] 的数量]
进阶:尝试以 O(n log k) 时间复杂度和 O(n) 空间复杂度解决。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/top-k-frequent-words
2.思路
(1)哈希表
① 使用 hashMap 来保存 words 中不同字符串以及对应出现的频率;
② 将hashMap 中的键值对存放到 list 中,然后再重写 list.sort() 中的排序规则:
1)如果单词出现频率相同,按字典顺序排序;
2)如果单词出现频率不同,按出现频率降序排序;
③ 取出 list 中前 k 个元素中的键并保存到 res 中,最后返回 res 即可。
(2)优先级队列
思路参考本题官方题解。
该方法的核心思想是:创建一个小根优先队列(即优先队列的队首元素最小)。我们将每一个字符串插入到优先队列中,如果优先队列的大小超过了 k,那么就将优先队列的队首元素弹出。这样最终优先队列中剩下的 k 个元素就是前 k 个出现次数最多的单词。
3.代码实现(Java)
//思路1————哈希表
class Solution {
public List<String> topKFrequent(String[] words, int k) {
List<String> res = new ArrayList<>();
// hashMap 保存 words 中不同字符串以及对应出现的频率
HashMap<String, Integer> hashMap = new HashMap<>();
for (String word : words) {
hashMap.put(word, hashMap.getOrDefault(word, 0) + 1);
}
List<Map.Entry<String, Integer>> list = new ArrayList<>(hashMap.entrySet());
list.sort((o1, o2) -> {
//当返回值为正数时,交换 o1 与 o2
if (o1.getValue().equals(o2.getValue())) {
//单词出现频率相同,按字典顺序排序
return o1.getKey().compareTo(o2.getKey());
} else {
//单词出现频率不同,按出现频率降序排序
return o2.getValue() - o1.getValue();
}
});
for(Map.Entry<String, Integer> map : list) {
if (k != 0) {
res.add(map.getKey());
k--;
} else {
break;
}
}
return res;
}
}
//思路2————优先级队列
class Solution {
public List<String> topKFrequent(String[] words, int k) {
List<String> res = new ArrayList<>();
// hashMap 保存 words 中不同字符串以及对应出现的频率
HashMap<String, Integer> hashMap = new HashMap<>();
for (String word : words) {
hashMap.put(word, hashMap.getOrDefault(word, 0) + 1);
}
PriorityQueue<Map.Entry<String, Integer>> queue = new PriorityQueue<>((entry1, entry2)->{
if (entry1.getValue().equals(entry2.getValue())) {
//单词出现频率相同,按字典顺序排序
return entry2.getKey().compareTo(entry1.getKey());
} else {
//单词出现频率不同,按出现频率降序排序
return entry1.getValue() - entry2.getValue();
}
});
for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
queue.offer(entry);
if (queue.size() > k) {
queue.poll();
}
}
while (!queue.isEmpty()) {
res.add(queue.poll().getKey());
}
Collections.reverse(res);
return res;
}
}
边栏推荐
- 服务器小常识
- Promise in detail
- Three-column layout implementation
- 2. 依赖管理和自动配置
- ROS Experimental Notes - Install QPEP and Intel-MKL
- nodejs项目连接mysql数据库
- C language, operators of shift operators (> >, < <) explanation
- Summary of Confused Knowledge Points for "High Items" in the Soft Examination in the Second Half of 2022 (2)
- 多语种翻译-多语种翻译软件免费
- NOR FLASH闪存芯片ID应用之软件保护场景
猜你喜欢
![[C] the C language program design, dynamic address book (order)](/img/bb/b44066e91219a57b653e330198e4a0.png)
[C] the C language program design, dynamic address book (order)
![[Excel knowledge and skills] Convert text numbers to numeric format](/img/7e/16a068025ec2639b343436c7f5b245.png)
[Excel knowledge and skills] Convert text numbers to numeric format

Design and implementation of flower online sales management system

有哪些可以投稿软件工程/系统软件/程序设计语言类外文期刊、会议?

8. WEB 开发-静态资源访问

从0开始设计JVM ,忘记名词跟上思路一次搞懂

10. Notes on receiving parameters

Web APIs BOM- 操作浏览器之综合案例
![[C language] Detailed explanation of data storage](/img/3f/3799a3ba0f2642272e15bd7a3e511f.png)
[C language] Detailed explanation of data storage

Software Testing Certificate (1) - Software Evaluator
随机推荐
“蔚来杯“2022牛客暑期多校训练营2 DGHJKL题解
[Excel knowledge and skills] Convert text numbers to numeric format
如何便捷获取参考文献的引用格式?
Mysql. Slow Sql
[21-day learning challenge - kernel notes] (5) - devmem read and write register debugging
In 22 years, the salary of programmers nationwide in January was released, only to know that there are so many with annual salary of more than 400,000?
李彦宏拆墙交朋友,大厂“塑料友情”能否帮百度啃下硬骨头?
多语种翻译-多语种翻译软件免费
CF1286E-Fedya the Potter Strikes Back【KMP,RMQ】
I caught a 10-year-old Ali test developer, and after talking about it, I made a lot of money...
14. Thymeleaf
如何利用原生JS实现回到顶部以及吸顶效果
Software Testing Certificate (1) - Software Evaluator
How to do patent mining, the key is to find patent points, in fact, it is not too difficult
特殊类与类型转换
[Excel知识技能] 将文本型数字转换为数值格式
12. 处理 JSON
鲲鹏编译调试及原生开发工具基础知识
[21天学习挑战赛——内核笔记](五)——devmem读写寄存器调试
只会懒汉式和饿汉式 你还不懂单例模式!