标签:count numberFrequencyMap Elements num int Top Element pq Frequent
Link: https://leetcode.com/problems/top-k-frequent-elements/
Constraints:
1 <= nums.length <= 105
k is in the range [1, the number of unique elements in the array].
It is guaranteed that the answer is unique.
Idea
We could use priority heap to keep track of the K least frequent elements, by implementing our own comparator. Everytime the size of the heap is larger than K, we pop elemnt from the heap. This way we make sure the remaining K elements are the most frequent.
Code
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> numberFrequencyMap = new HashMap<>();
for (int n : nums) {
if (!numberFrequencyMap.containsKey(n)) {
numberFrequencyMap.put(n, 1);
} else {
numberFrequencyMap.put(n, numberFrequencyMap.get(n) + 1);
}
}
PriorityQueue<Element> pq = new PriorityQueue<>();
for (int n : numberFrequencyMap.keySet()) {
Element element = new Element(n, numberFrequencyMap.get(n));
pq.offer(element);
while (pq.size() > k) {
pq.poll();
}
}
int[] results = new int[k];
for (int i = 0; i < k && !pq.isEmpty(); i++) {
Element element = pq.poll();
results[i] = element.num;
}
return results;
}
private class Element implements Comparable<Element> {
int num;
int count;
Element(int num, int count) {
this.num = num;
this.count = count;
}
@Override
public int compareTo(Element other) {
return this.count - other.count;
}
}
}
- Time: O(nlogk) as the time to do offer()/poll() against a min heap with size k is (logk).
- Space: O(n). The map needs to have a entry for all unique words in the array.
This question can also be solved using Bucket sort with O(n) time, as shown in this link.
Similar problem:
标签:count,numberFrequencyMap,Elements,num,int,Top,Element,pq,Frequent 来源: https://www.cnblogs.com/blackraven25/p/15119919.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。