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;
}
}

最新文章

  1. PHP求职宝典系列——PHP Web 编程篇
  2. hdu4405 Aeroplane chess
  3. C# webBrowser 开新窗口保持Session(转)
  4. pip install 报错原因
  5. sdut1598 周游列国【简单模拟题】
  6. JMeter处理jdbc请求后的响应结果
  7. windows下react-native环境搭建
  8. JQuery基础教程:事件(下)
  9. sed命令教程
  10. 无法读取配置节 system.serviceModel 因为它缺少节声明的解决方法
  11. HUST 1600 Lucky Numbers
  12. Review: Command-line about Git
  13. spring cloud + .net core实现微服务架构
  14. ESP8266 软件实现 Delta-sigma(ΔΣ)调制器 并通过I2S接口输出编码流
  15. 观光公交 [NOIP 2011] [思维推导]
  16. IDEA 下载 和 安装 22
  17. 2019/1/9 6系列所有装置编号与SIM卡信息抓取
  18. 大数据之Flume
  19. Redis cluster集群:原理及搭建
  20. 逆袭之旅DAY16.东软实训.Oracle.修改用户

热门文章

  1. pycharm和python安装
  2. git登录账号密码错误remote: Incorrect username or password (access token)
  3. Navicat mysql 数据库备份和使用,备份以后是nb3文件
  4. elastic启动脚本
  5. 游戏引擎UE4详解!
  6. Numa解释
  7. CommandNotFoundError: No command &#39;conda conda&#39;.
  8. vue项目开始 首页 part1
  9. js根据当前日期 求一个月前 半年前 一年前的日期
  10. CSS——fixed 固定定位相对于父容器