mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
添加 0347.前 K 个高频元素.md Java版本
This commit is contained in:
@ -133,7 +133,59 @@ public:
|
|||||||
|
|
||||||
|
|
||||||
Java:
|
Java:
|
||||||
|
```java
|
||||||
|
public class N0347 {
|
||||||
|
/**
|
||||||
|
* 解法:
|
||||||
|
* 1.统计频次。O(n)
|
||||||
|
* 2.排序。O(nlogn)
|
||||||
|
* 3.取前K个元素
|
||||||
|
*
|
||||||
|
* 注意到,排序的时候需要用小顶堆,而不是大顶堆。因为每次需要把最小的堆顶弹出去,最后才剩下最大的k个。
|
||||||
|
* 时间复杂度:O(n + nlogk) = O(nlogk)
|
||||||
|
*/
|
||||||
|
public int[] topKFrequent(int[] nums, int k) {
|
||||||
|
HashMap<Integer, Integer> map = statistic(nums);
|
||||||
|
|
||||||
|
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
|
||||||
|
@Override
|
||||||
|
public int compare(Integer o1, Integer o2) {
|
||||||
|
return map.get(o1) - map.get(o2);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
for (Integer key : map.keySet()) {
|
||||||
|
if (pq.size() < k) {
|
||||||
|
pq.offer(key);
|
||||||
|
} else if (map.get(pq.peek()) < map.get(key)){
|
||||||
|
pq.poll();
|
||||||
|
pq.offer(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int[] result = new int[k];
|
||||||
|
for (int i = 0; i < k; i++) {
|
||||||
|
result[i] = pq.poll();
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// key: 值,value:次数
|
||||||
|
private HashMap<Integer, Integer> statistic(int[] nums) {
|
||||||
|
HashMap<Integer, Integer> map = new HashMap<>();
|
||||||
|
for (int num : nums) {
|
||||||
|
if (map.get(num) == null) {
|
||||||
|
map.put(num, 1);
|
||||||
|
} else {
|
||||||
|
map.put(num, map.get(num) + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user