From 1c390b3562b03be7a24933455b76a9187996ff72 Mon Sep 17 00:00:00 2001 From: xqsrpanz Date: Fri, 26 Apr 2024 18:01:03 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=BA=86=20JavaScript=20?= =?UTF-8?q?=E8=A7=A3=E6=B3=95=E4=BA=8C=EF=BC=8C=E5=A0=86=20pop=20=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E6=97=A0=E6=B3=95=E5=A4=84=E7=90=86=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E9=95=BF=E5=BA=A6=20<=3D=201=20=E7=9A=84=E8=BE=B9=E7=95=8C?= =?UTF-8?q?=E6=83=85=E5=86=B5=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0347.前K个高频元素.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 34d9f82c..8a219c6a 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -405,6 +405,11 @@ class Heap { // 获取堆顶元素并移除 pop() { + // 边界情况,只有一个元素或没有元素应直接弹出 + if (this.size() <= 1) { + return this.queue.pop() + } + // 堆顶元素 const out = this.queue[0]; @@ -608,3 +613,4 @@ impl Solution { + From bcdf3e4ecdf352ee5f6a9d539bd980c66c3ea93e Mon Sep 17 00:00:00 2001 From: xqsrpanz <129468278+xqsrpanz@users.noreply.github.com> Date: Fri, 26 Apr 2024 19:45:18 +0800 Subject: [PATCH 2/2] =?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 1. 修复了 JavaScript 解法二,堆 pop 方法无法处理数组长度 <= 1 的边界情况的问题 2. 删除了有误导性的条件判断。事实上,被删除的表达式永远为真(searchChild !== undefined)。原作者想表达的意思可能是 this.queue[searchChild] !== undefined,而实际上,这个判断也是不必要的,这种情况会被后续的 this.compare(index, searchChild) > 0 判断排除。但鉴于本项目的教程性质,直接去除可能会导致语义不清,考虑酌情将原处替换为 this.queue[searchChild] !== undefined 或直接删除 --- problems/0347.前K个高频元素.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 8a219c6a..cca9b0ed 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -421,7 +421,7 @@ class Heap { let left = 1; // left 是左子节点下标 left + 1 则是右子节点下标 let searchChild = this.compare(left, left + 1) > 0 ? left + 1 : left; - while (searchChild !== undefined && this.compare(index, searchChild) > 0) { // 注意compare参数顺序 + while (this.compare(index, searchChild) > 0) { // 注意compare参数顺序 [this.queue[index], this.queue[searchChild]] = [this.queue[searchChild], this.queue[index]]; // 更新下标