mirror of
https://github.com/krahets/hello-algo.git
synced 2026-05-02 14:33:06 +08:00
build
This commit is contained in:
@@ -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#"
|
||||
|
||||
Reference in New Issue
Block a user