diff --git a/chapter_appendix/contribution.md b/chapter_appendix/contribution.md index 26452ad8f..c4711e36e 100644 --- a/chapter_appendix/contribution.md +++ b/chapter_appendix/contribution.md @@ -4,9 +4,9 @@ comments: true # 16.2 一起参与创作 -由于作者能力有限,书中难免存在一些遗漏和错误,请您谅解。如果您发现了笔误、失效链接、内容缺失、文字歧义、解释不清晰或行文结构不合理等问题,请协助我们进行修正,以帮助其他读者获得更优质的学习资源。 +由于作者能力有限,书中难免存在一些遗漏和错误,请您谅解。如果您发现了笔误、失效链接、内容缺失、文字歧义、解释不清晰或行文结构不合理等问题,请协助我们进行修正,以给读者提供更优质的学习资源。 -所有[撰稿人](https://github.com/krahets/hello-algo/graphs/contributors)的 GitHub ID 将在仓库、网页版和 PDF 版的主页上进行展示,以感谢他们对开源社区的无私奉献。 +所有[撰稿人](https://github.com/krahets/hello-algo/graphs/contributors)的 GitHub ID 将被展示在本书的仓库主页上,以感谢他们对开源社区的无私奉献。 !!! success "开源的魅力" @@ -40,11 +40,9 @@ comments: true ### 3. Docker 部署 -执行以下 Docker 脚本,稍等片刻,即可在网页 `http://localhost:8000` 访问本项目。 +在 `hello-algo` 根目录下,执行以下 Docker 脚本,即可在 `http://localhost:8000` 访问本项目。 ```shell -git clone https://github.com/krahets/hello-algo.git -cd hello-algo docker-compose up -d ``` diff --git a/chapter_heap/top_k.md b/chapter_heap/top_k.md index 8de4a252e..508dd76f7 100644 --- a/chapter_heap/top_k.md +++ b/chapter_heap/top_k.md @@ -205,13 +205,51 @@ comments: true === "JS" ```javascript title="top_k.js" - [class]{}-[func]{topKHeap} + /* 基于堆查找数组中最大的 k 个元素 */ + function topKHeap(nums, k) { + // 使用大顶堆 MaxHeap,对数组 nums 取相反数 + const invertedNums = nums.map((num) => -num); + // 将数组的前 k 个元素入堆 + const heap = new MaxHeap(invertedNums.slice(0, k)); + // 从第 k+1 个元素开始,保持堆的长度为 k + for (let i = k; i < invertedNums.length; i++) { + // 若当前元素小于堆顶元素,则将堆顶元素出堆、当前元素入堆 + if (invertedNums[i] < heap.peek()) { + heap.pop(); + heap.push(invertedNums[i]); + } + } + // 取出堆中元素 + const maxHeap = heap.getMaxHeap(); + // 对堆中元素取相反数 + const invertedMaxHeap = maxHeap.map((num) => -num); + return invertedMaxHeap; + } ``` === "TS" ```typescript title="top_k.ts" - [class]{}-[func]{topKHeap} + /* 基于堆查找数组中最大的 k 个元素 */ + function topKHeap(nums: number[], k: number): number[] { + // 将堆中所有元素取反,从而用大顶堆来模拟小顶堆 + const invertedNums = nums.map((num) => -num); + // 将数组的前 k 个元素入堆 + const heap = new MaxHeap(invertedNums.slice(0, k)); + // 从第 k+1 个元素开始,保持堆的长度为 k + for (let i = k; i < invertedNums.length; i++) { + // 若当前元素小于堆顶元素,则将堆顶元素出堆、当前元素入堆 + if (invertedNums[i] < heap.peek()) { + heap.pop(); + heap.push(invertedNums[i]); + } + } + // 取出堆中元素 + const maxHeap = heap.getMaxHeap(); + // 对堆中元素取相反数 + const invertedMaxHeap = maxHeap.map((num) => -num); + return invertedMaxHeap; + } ``` === "Dart" diff --git a/index.md b/index.md index 81a3af132..eb668b3e6 100644 --- a/index.md +++ b/index.md @@ -84,9 +84,9 @@ hide: