From 7111943ac00f9cea2c4899f0211b2d0fcadeef62 Mon Sep 17 00:00:00 2001 From: BanTanger <88583317+BanTanger@users.noreply.github.com> Date: Thu, 13 Apr 2023 22:18:21 +0800 Subject: [PATCH] =?UTF-8?q?Update=200347.=E5=89=8DK=E4=B8=AA=E9=AB=98?= =?UTF-8?q?=E9=A2=91=E5=85=83=E7=B4=A0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 之前的 java 代码调用的 api 过于难记忆,不利于白板书写,于是将优先级队列存储数据结构从 map.setEntry 改为 int[] 数组,方便大家记忆理解书写 --- problems/0347.前K个高频元素.md | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 0d268d9b..6c8b51b1 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -188,7 +188,33 @@ class Solution { } } ``` - +简化版代码: +```java +class Solution { + public int[] topKFrequent(int[] nums, int k) { + // 优先级队列,为了避免复杂 api 操作,pq 存储数组 + // lambda 表达式设置优先级队列从大到小存储 o1 - o2 为从大到小,o2 - o1 反之 + PriorityQueue pq = new PriorityQueue<>((o1, o2) -> o1[1] - o2[1]); + int[] res = new int[k]; // 答案数组为 k 个元素 + Map map = new HashMap<>(); // 记录元素出现次数 + for(int num : nums) map.put(num, map.getOrDefault(num, 0) + 1); + for(var x : map.entrySet()) { // entrySet 获取 k-v Set 集合 + // 将 kv 转化成数组 + int[] tmp = new int[2]; + tmp[0] = x.getKey(); + tmp[1] = x.getValue(); + pq.offer(tmp); + if(pq.size() > k) { + pq.poll(); + } + } + for(int i = 0; i < k; i ++) { + res[i] = pq.poll()[0]; // 获取优先队列里的元素 + } + return res; + } +} +``` Python: ```python