添加 0347.前 K 个高频元素.md Java版本

This commit is contained in:
h2linlin
2021-05-13 21:59:23 +08:00
parent fddb778dbe
commit f6b32b55b3

View File

@ -133,7 +133,59 @@ public:
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