diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 9ec601a7..0e70f553 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -134,59 +134,33 @@ public: Java: ```java -public class N0347 { - /** - * 解法: - * 1.统计频次。O(n) - * 2.排序。O(nlogn) - * 3.取前K个元素 - * - * 注意到,排序的时候需要用小顶堆,而不是大顶堆。因为每次需要把最小的堆顶弹出去,最后才剩下最大的k个。 - * 时间复杂度:O(n + nlogk) = O(nlogk) - */ + +class Solution { 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]; + HashMap map = new HashMap<>(); + for (int num : nums) { + map.put(num, map.getOrDefault(num, 0) + 1); } - int[] result = new int[k]; - for (int i = 0; i < k; i++) { - result[i] = pq.poll(); + Set> entries = map.entrySet(); + // 根据map的value值正序排,相当于一个小顶堆 + PriorityQueue> queue = new PriorityQueue<>((o1, o2) -> o1.getValue() - o2.getValue()); + for (Map.Entry entry : entries) { + queue.offer(entry); + if (queue.size() > k) { + queue.poll(); + } + } + for (int i = k - 1; i >= 0; i--) { + result[i] = queue.poll().getKey(); } 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: