您的位置:首页 > 产品设计 > UI/UE

Top K Frequent Elements

2016-08-09 09:02 197 查看
有一个Map对象,这时候使用keySet()方法获取所有的key值

先遍历一遍数组将每个数字以及其出现的次数保存到hash表里。
构建一个以出现次数为索引的list,次数最多为n,所以list长度为n+1
再遍历hash的value,按照value的值即出现次数作为索引将其对应的key存到构建好的list中。注意list的元素为ArrayList这样可以保证出现次数相同的元素都被添加统计进来。

public class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
List<Integer>[] bucket = new List[nums.length + 1];
Map<Integer, Integer> frequencyMap = new HashMap<Integer, Integer>();

for (int n : nums) {
<pre name="code" class="java" style="color: rgb(51, 51, 51); font-size: 16px; line-height: 28px; text-align: justify;">//取map里的值,如果为空就默认为零。取出来之后加一,统计次数
frequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1); }//遍历map,取所有的key如果这个key在原来的list中为空那么新建一个链表 将关键字添加到链表中for (int key : frequencyMap.keySet()) {int frequency = frequencyMap.get(key);if (bucket[frequency] == null) {bucket[frequency]
= new ArrayList<>();}bucket[frequency].add(key);}//统计次数List<Integer> res = new ArrayList<>();//取k个值for (int pos = bucket.length - 1; pos >= 0 && res.size() < k; pos--) {if (bucket[pos] != null) {res.addAll(bucket[pos]);}}return res;}}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: