From 097051e1bbd06e3302f832c8e0d9179cc54d6c02 Mon Sep 17 00:00:00 2001 From: dxiaofeng <106021460+dxiaofeng@users.noreply.github.com> Date: Tue, 24 Oct 2023 10:52:23 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=AD=A30347.=E5=89=8DK=E4=B8=AA?= =?UTF-8?q?=E9=AB=98=E9=A2=91=E5=85=83=E7=B4=A0Java=E7=AE=80=E6=98=93?= =?UTF-8?q?=E7=89=88=E4=BB=A3=E7=A0=81=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0347.前K个高频元素.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index b3063111..4830f9a3 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -193,7 +193,7 @@ class Solution { class Solution { public int[] topKFrequent(int[] nums, int k) { // 优先级队列,为了避免复杂 api 操作,pq 存储数组 - // lambda 表达式设置优先级队列从大到小存储 o1 - o2 为从大到小,o2 - o1 反之 + // 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<>(); // 记录元素出现次数 @@ -204,6 +204,7 @@ class Solution { tmp[0] = x.getKey(); tmp[1] = x.getValue(); pq.offer(tmp); + // 下面的代码是根据小根堆实现的,我只保留优先队列的最后的k个,只要超出了k我就将最小的弹出,剩余的k个就是答案 if(pq.size() > k) { pq.poll(); }