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) {
= 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;}}
先遍历一遍数组将每个数字以及其出现的次数保存到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;}}
相关文章推荐
- LeetCode--No.347--Top K Frequent Elements
- Top K Frequent Elements
- leetcode之Top K Frequent Elements
- leetcode347 Top K Frequent Elements java
- 【leetcode】Top K Frequent Elements
- Top K Frequent Elements解题报告
- LeetCode 347 Top K Frequent Elements (HashMap && TreeMap 或 PriorityQueue 推荐)
- LeetCode : Top K Frequent Elements
- Top K Frequent Elements
- LeetCode:Top K Frequent Elements
- [LC347] Top K Frequent Elements
- LeetCode No.347 Top K Frequent Elements
- [Leetcode] #347 Top K Frequent Elements
- LeetCode[347] Top K Frequent Elements
- Top K Frequent Elements
- Top K Frequent Elements
- LeetCode.347(692) Top K Frequent Elements && Top K Frequent Words
- week12-leetcode #347-Top-K-Frequent-Elements
- leetcode 347 Top K Frequent Elements C++
- [LeetCode] Top K Frequent Elements