Leetcode no. 347
2016-06-24 13:50
134 查看
347. Top K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
public class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
List<Integer> res= new LinkedList<>();
List<Integer>[] buckets= new List[nums.length+1];
Map<Integer, Integer> map= new HashMap<>();
for (int ele: nums) {
map.put(ele, map.getOrDefault(ele, 0)+1);
}
for (int key: map.keySet()) {
int fre= map.get(key);
if (buckets[fre]== null) buckets[fre]= new LinkedList<>();
buckets[fre].add(key);
}
for (int i = buckets.length-1; i >= 0 && res.size()<k; i--) {
if (buckets[i]!= null) res.addAll(buckets[i]);
}
return res;
}
}
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given
[1,1,1,2,2,3]and k = 2, return
[1,2].
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
public class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
List<Integer> res= new LinkedList<>();
List<Integer>[] buckets= new List[nums.length+1];
Map<Integer, Integer> map= new HashMap<>();
for (int ele: nums) {
map.put(ele, map.getOrDefault(ele, 0)+1);
}
for (int key: map.keySet()) {
int fre= map.get(key);
if (buckets[fre]== null) buckets[fre]= new LinkedList<>();
buckets[fre].add(key);
}
for (int i = buckets.length-1; i >= 0 && res.size()<k; i--) {
if (buckets[i]!= null) res.addAll(buckets[i]);
}
return res;
}
}
相关文章推荐
- iOS开发之单元测试/Unit Tests
- Linux下重启tomcat
- R把科学计数法表示的数字转化为文本
- android 设置系统屏幕亮度
- mysql 主从master-slave同步复制 配置,为读写分离准备
- Android应用开发之(通过ClipboardManager, ClipData进行复制粘贴)
- python微教程---第一季(第三集)---- 数据结构(列表)
- GIS离线地图瓦片的生成及发布
- 面试3+ 动软代码生成器
- mybatis反转自动生成dao、实体类和mapper.xml
- Swagger介绍-一套流行的API框架
- Android LinearLayout实现下拉刷新
- fopen()
- SharePoint2013TimerJob计时器发送邮件
- windows下为mysql添加日志
- iOS软件开发获取相机图片处理
- 学会识别数据线!真的有必要!
- 多线程下载
- list集合和数组如何互相转化
- 【操作系统】实验四 主存空间的分配和回收