347. Top K Frequent Elements
程序员文章站
2022-03-07 19:44:19
...
There are several ways to solve this problem. The approach that we are going to focus on here is called Bucket Sort. For details of Bucket Sort, you can visit this website: 点击打开链接. Here is a visualization of Bucket Sort: 点击打开链接.
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) {
frequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1);
}
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<>();
for (int pos = bucket.length - 1; pos >= 0 && res.size() < k; pos--) {
if (bucket[pos] != null) {
res.addAll(bucket[pos]);
}
}
return res;
}
It is obvious that the running time for this approach is O(n). 上一篇: LeetCode 347. Top K Frequent Elements解题报告(python)
下一篇: LeetCode 力扣 347. 前 K 个高频元素 top k frequent elements hashmap 优先队列 priorityqueue
推荐阅读
-
LeetCode刷题笔记(Top K Frequent Elements)
-
TOP K frequent-elements
-
LeetCode 692. Top K Frequent Words
-
Leetcode 692. Top K Frequent Words
-
692. Top K Frequent Words
-
LeetCode 347: 前 K 个高频元素 Top K Frequent Elements
-
Top K Frequent Elements
-
(Java)leetcode-347 Top K Frequent Elements
-
[Leetcode] Top K Frequent Elements
-
LeetCode 347. Top K Frequent Elements