diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 1902bd68..9ec601a7 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -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 map = statistic(nums); + PriorityQueue pq = new PriorityQueue<>(new Comparator() { + @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 statistic(int[] nums) { + HashMap 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: