[LC] 347. Top K Frequent Elements
2024-08-31 12:48:53
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for (Integer num: nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
// keep a top frequency heap
PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>((a, b) ->
a.getValue() == b.getValue() ? b.getKey().compareTo(a.getKey()): a.getValue() - b.getValue()
);
for (Map.Entry<Integer, Integer> entry: map.entrySet()) {
pq.offer(entry);
if (pq.size() > k) {
pq.poll();
}
}
List<Integer> res = new ArrayList<>();
// while (!pq.isEmpty()) {
// res.add(0, pq.poll().getKey());
// }
while (!pq.isEmpty()) {
res.add(pq.poll().getKey());
}
return res;
}
}
public class Solution {
public String[] topKFrequent(String[] combo, int k) {
// Write your solution here.
Map<String, Integer> map = new HashMap<>();
for (String s: combo) {
map.put(s, map.getOrDefault(s, 0) + 1);
}
PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>(k, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> a, Map.Entry<String, Integer> b) {
return a.getValue().compareTo(b.getValue());
}
});
for (Map.Entry<String, Integer> mymap: map.entrySet()) {
pq.offer(mymap);
if (pq.size() > k) {
pq.poll();
}
}
String[] res = new String[pq.size()];
for (int i = res.length - 1; i >= 0; i--) {
res[i] = pq.poll().getKey();
}
return res;
}
}
最新文章
- PHP求职宝典系列——PHP Web 编程篇
- hdu4405 Aeroplane chess
- C# webBrowser 开新窗口保持Session(转)
- pip install 报错原因
- sdut1598 周游列国【简单模拟题】
- JMeter处理jdbc请求后的响应结果
- windows下react-native环境搭建
- JQuery基础教程:事件(下)
- sed命令教程
- 无法读取配置节 system.serviceModel 因为它缺少节声明的解决方法
- HUST 1600 Lucky Numbers
- Review: Command-line about Git
- spring cloud + .net core实现微服务架构
- ESP8266 软件实现 Delta-sigma(ΔΣ)调制器 并通过I2S接口输出编码流
- 观光公交 [NOIP 2011] [思维推导]
- IDEA 下载 和 安装 22
- 2019/1/9 6系列所有装置编号与SIM卡信息抓取
- 大数据之Flume
- Redis cluster集群:原理及搭建
- 逆袭之旅DAY16.东软实训.Oracle.修改用户
热门文章
- pycharm和python安装
- git登录账号密码错误remote: Incorrect username or password (access token)
- Navicat mysql 数据库备份和使用,备份以后是nb3文件
- elastic启动脚本
- 游戏引擎UE4详解!
- Numa解释
- CommandNotFoundError: No command &#39;conda conda&#39;.
- vue项目开始 首页 part1
- js根据当前日期 求一个月前 半年前 一年前的日期
- CSS——fixed 固定定位相对于父容器