LeetCode-Top K Frequent Elements
2016-08-11 12:40
399 查看
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
Analysis:
We can use bucket sort style solution: Since the largest frequency is N, we can use a size N array to store the element with each possible frequency.
Solution:
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
Analysis:
We can use bucket sort style solution: Since the largest frequency is N, we can use a size N array to store the element with each possible frequency.
Solution:
public class Solution { public List<Integer> topKFrequent(int[] nums, int k) { List<Integer> res = new ArrayList<Integer>(); if (nums.length==0 || k==0) return res; List<Integer>[] freqList = new List[nums.length+1]; Map<Integer,Integer> freqMap = new HashMap<Integer,Integer>(); // Get frequencey map for (int num: nums){ freqMap.put(num,freqMap.getOrDefault(num,0)+1); } // According to each num's frequency, put it into frequency list for (int num: freqMap.keySet()){ int freq = freqMap.get(num); if (freqList[freq]==null){ freqList[freq] = new ArrayList<Integer>(); } freqList[freq].add(num); } int left = k; for (int i=freqList.length-1;i>=0 && left>0;i--){ if (freqList[i]!=null){ if (left>=freqList[i].size()){ res.addAll(freqList[i]); left -= freqList[i].size(); } else { for (int j=0;j<left;j++) res.add(freqList[i].get(j)); break; } } } return res; } }
相关文章推荐
- leetcode_347 Top K Frequent Elements
- leetcode_c++:哈希:Top K Frequent Elements(347)
- LeetCode 347 Top K Frequent Elements (HashMap && TreeMap 或 PriorityQueue 推荐)
- LeetCode--No.347--Top K Frequent Elements
- leetcode 347[medium]--Top K Frequent Elements
- [LeetCode] Top K Frequent Elements 前K个高频元素
- [LeetCode] Top K Frequent Elements
- LeetCode Top K Frequent Elements
- leetcode 347 Top K Frequent Elements C++
- Leetcode Top K Frequent Elements
- LeetCode No.347 Top K Frequent Elements
- Java [Leetcode 347]Top K Frequent Elements
- LeetCode "Top K Frequent Elements"
- 【Leetcode】Top K Frequent Elements
- LeetCode Top K Frequent Elements
- leetcode-347-Top K Frequent Elements
- Top K Frequent Elements=-leetcode
- leetcode347 Top K Frequent Elements java
- LeetCode : Top K Frequent Elements
- [LeetCode][Python]Top K Frequent Elements