mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-26 03:06:29 +08:00
e4ba690005
* feat(go): support hash map chaining * feat(go): support hash map open address * feat(go): support simple hash * feat(go): support top k heap * feat(go): support subset sum I * feat(go): support subset sum native * feat(go): support subset sum II * fix(go): fix some problem
49 lines
1.2 KiB
Go
49 lines
1.2 KiB
Go
// File: top_k.go
|
|
// Created Time: 2023-06-24
|
|
// Author: Reanon (793584285@qq.com)
|
|
|
|
package chapter_heap
|
|
|
|
import "container/heap"
|
|
|
|
type minHeap []any
|
|
|
|
func (h *minHeap) Len() int { return len(*h) }
|
|
func (h *minHeap) Less(i, j int) bool { return (*h)[i].(int) < (*h)[j].(int) }
|
|
func (h *minHeap) Swap(i, j int) { (*h)[i], (*h)[j] = (*h)[j], (*h)[i] }
|
|
|
|
// Push heap.Interface 的方法,实现推入元素到堆
|
|
func (h *minHeap) Push(x any) {
|
|
*h = append(*h, x.(int))
|
|
}
|
|
|
|
// Pop heap.Interface 的方法,实现弹出堆顶元素
|
|
func (h *minHeap) Pop() any {
|
|
// 待出堆元素存放在最后
|
|
last := (*h)[len(*h)-1]
|
|
*h = (*h)[:len(*h)-1]
|
|
return last
|
|
}
|
|
|
|
// Top 获取堆顶元素
|
|
func (h *minHeap) Top() any {
|
|
return (*h)[0]
|
|
}
|
|
|
|
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
|
|
}
|