diff --git a/codes/go/chapter_heap/heap_test.go b/codes/go/chapter_heap/heap_test.go index 4b84a05e55..3d0ad506a1 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/my_heap.go b/codes/go/chapter_heap/my_heap.go index 1cc091b2fd..c51ddb3ee7 100644 --- a/codes/go/chapter_heap/my_heap.go +++ b/codes/go/chapter_heap/my_heap.go @@ -79,7 +79,7 @@ func (h *maxHeap) push(val any) { /* 从节点 i 开始,从底至顶堆化 */ func (h *maxHeap) siftUp(i int) { - for true { + for { // 获取节点 i 的父节点 p := h.parent(i) // 当“越过根节点”或“节点无须修复”时,结束堆化 @@ -114,7 +114,7 @@ func (h *maxHeap) pop() any { /* 从节点 i 开始,从顶至底堆化 */ func (h *maxHeap) siftDown(i int) { - for true { + for { // 判断节点 i, l, r 中值最大的节点,记为 max l, r, max := h.left(i), h.right(i), i if l < h.size() && h.data[l].(int) > h.data[max].(int) { diff --git a/codes/go/chapter_heap/top_k.go b/codes/go/chapter_heap/top_k.go index 4874c3fb15..a8c4289f0b 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])