From 974a75f1a025aa93d2fcd55758a4b5e73efb0c65 Mon Sep 17 00:00:00 2001 From: xiaok29 <1526783667@qq.com> Date: Thu, 20 Jun 2024 15:50:04 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9E=20fix:?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit If k is greater than the array itself, directly return itself --- codes/go/chapter_heap/heap_test.go | 5 +++++ codes/go/chapter_heap/top_k.go | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/codes/go/chapter_heap/heap_test.go b/codes/go/chapter_heap/heap_test.go index 4b84a05e5..3d0ad506a 100644 --- a/codes/go/chapter_heap/heap_test.go +++ b/codes/go/chapter_heap/heap_test.go @@ -98,4 +98,9 @@ func TestTopKHeap(t *testing.T) { res := topKHeap(nums, k) fmt.Printf("最大的 " + strconv.Itoa(k) + " 个元素为") PrintHeap(*res) + + k = 10 + res = topKHeap(nums, k) + fmt.Printf("最大的 " + strconv.Itoa(k) + " 个元素为") + PrintHeap(*res) } diff --git a/codes/go/chapter_heap/top_k.go b/codes/go/chapter_heap/top_k.go index 4874c3fb1..a8c4289f0 100644 --- a/codes/go/chapter_heap/top_k.go +++ b/codes/go/chapter_heap/top_k.go @@ -35,6 +35,16 @@ func topKHeap(nums []int, k int) *minHeap { // 初始化小顶堆 h := &minHeap{} heap.Init(h) + + // 如果k大于数组本身返回本身数组 + if len(nums) < k { + for _, num := range nums { + heap.Push(h, num) + } + + return h + } + // 将数组的前 k 个元素入堆 for i := 0; i < k; i++ { heap.Push(h, nums[i])