diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 1902bd68..6e94a6ea 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -133,7 +133,31 @@ public: Java: +```java +class Solution { + public int[] topKFrequent(int[] nums, int k) { + int[] result = new int[k]; + HashMap map = new HashMap<>(); + for (int num : nums) { + map.put(num, map.getOrDefault(num, 0) + 1); + } + 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; + } +} +``` Python: