【发布时间】:2026-01-29 03:45:01
【问题描述】:
尝试使用https://pkg.go.dev/container/heap 包编写我自己的具有固定容量的 Go PriorityQueue,并将算法从 http://stevehanov.ca/blog/?id=122,如下:
def heapSearch( bigArray, k ):
heap = []
# Note: below is for illustration. It can be replaced by
# heapq.nlargest( bigArray, k )
for item in bigArray:
# If we have not yet found k items, or the current item is larger than
# the smallest item on the heap,
if len(heap) < k or item > heap[0]:
# If the heap is full, remove the smallest element on the heap.
if len(heap) == k: heapq.heappop( heap )
# add the current element as the new smallest.
heapq.heappush( heap, item )
return heap
我想出了这个——https://play.golang.org/p/VmPURbWSmIA
for value, priority := range items {
// If we have not yet found k items, or the current item is larger than
// the smallest item on the heap,
if len(pq) < k || value > pq[0].value {
// If the heap is full, remove the smallest element on the heap.
if len(pq) == k {
pq.Pop()
}
// add the current element as the new smallest.
pq.Push(&Item{
value: value,
priority: priority,
})
}
heap.Init(&pq)
}
但是,仍有一些问题。
请问有人帮忙改正吗?
PS。 heap.Init(&pq) 之前不在循环中,但因为 Priority queues in GO 而移到了那里:
调用 heap.Init(&pq) 将对整个堆进行排序
PPS:
更多失败尝试:
【问题讨论】:
-
Python 代码使用最小堆找到最大的 N 个项目:即,在堆中,元素 0 是最小的,因为堆属性具有 h[i] h[2i],等等。要找到最大的 N,你必须建立一个最小堆,而不是最大堆。
-
除此之外,要使用 Go
heap函数,您必须调用heap.Push和heap.Pop,而不是pq.Push和pq.Pop。既然你想建立一个最大堆,你仍然可以这样做,如果它的优先级超过现有的最大优先级,你只想强制新项目进入堆。不幸的是,现在没有简单的方法来找到最小项要丢弃。 -
请详细说明一下。这就是你所说的最小堆——play.golang.org/p/WdUx8l9dvH1@torek?
-
嗯,是的,但您通常会使用
<来作为Less函数。 -
我首先尝试了
<,但这给了我索引超出范围的错误,:( :(
标签: algorithm go heap priority-queue