This commit is contained in:
krahets
2023-07-24 13:09:43 +08:00
parent debd909387
commit 0760e0865e
14 changed files with 715 additions and 38 deletions

View File

@@ -139,7 +139,24 @@ comments: true
=== "Go"
```go title="top_k.go"
[class]{maxHeap}-[func]{topKHeap}
/* 基于堆查找数组中最大的 k 个元素 */
func topKHeap(nums []int, k int) *minHeap {
h := &minHeap{}
heap.Init(h)
// 将数组的前 k 个元素入堆
for i := 0; i < k; i++ {
heap.Push(h, nums[i])
}
// 从第 k+1 个元素开始,保持堆的长度为 k
for i := k; i < len(nums); i++ {
// 若当前元素大于堆顶元素,则将堆顶元素出堆、当前元素入堆
if nums[i] > h.Top().(int) {
heap.Pop(h)
heap.Push(h, nums[i])
}
}
return h
}
```
=== "JavaScript"
@@ -157,7 +174,7 @@ comments: true
=== "C"
```c title="top_k.c"
[class]{maxHeap}-[func]{topKHeap}
[class]{}-[func]{topKHeap}
```
=== "C#"