From 85e0d6c85d593339152483a3fea33ab23cdcd5b3 Mon Sep 17 00:00:00 2001 From: AronJudge <2286381138@qq.com> Date: Mon, 11 Jul 2022 11:06:51 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B00347=20=E5=89=8DK=E4=B8=AA?= =?UTF-8?q?=E9=AB=98=E9=A2=91=E5=85=83=E7=B4=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 由原来的构建小顶堆改为构建大顶堆,减少部分代码逻辑,并增加了注释 通过LeetCode提交代码,修改后的执行时间更快。 --- problems/0347.前K个高频元素.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index a04041cc..0c978b2a 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -141,13 +141,10 @@ class Solution { } Set> entries = map.entrySet(); - // 根据map的value值正序排,相当于一个小顶堆 - PriorityQueue> queue = new PriorityQueue<>((o1, o2) -> o1.getValue() - o2.getValue()); + // 根据map的value值,构建于一个大顶堆(o1 - o2: 小顶堆, o2 - o1 : 大顶堆) + PriorityQueue> queue = new PriorityQueue<>((o1, o2) -> o2.getValue() - o1.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();