Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

If k is greater than the array itself, directly return itself #1401

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions codes/go/chapter_heap/heap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
4 changes: 2 additions & 2 deletions codes/go/chapter_heap/my_heap.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
// 当“越过根节点”或“节点无须修复”时,结束堆化
Expand Down Expand Up @@ -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) {
Expand Down
10 changes: 10 additions & 0 deletions codes/go/chapter_heap/top_k.go
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
Loading