Ayu*_*pta 7 heap priority-queue go
我试图使用heap实现一个示例程序,并且我能够 Push
往返Pop
于堆。我能够实现 Push 和 Pop 方法并按如下方式使用它们:
import "container/heap"
type Meeting struct {
start int
end int
}
func NewMeeting(times []int) *Meeting {
return &Meeting{start: times[0], end: times[1] }
}
type PQ []*Meeting
func (pq PQ) Len() int {
return len(pq)
}
func (pq PQ) Less(i, j int) bool {
return pq[i].end < pq[j].end
}
func (pq PQ) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
}
func (pq *PQ) Push(x interface{}) {
item := x.(*Meeting)
*pq = append(*pq, item)
}
func (pq *PQ) Pop() interface{} {
old := *pq
n := len(old)
item := old[n-1]
old[n-1] = nil // avoid memory leak
*pq = old[0 : n-1]
return item
}
func minMeetingRooms(intervals [][]int) int {
pq := make(PQ, 0)
heap.Init(&pq)
heap.Push(&pq, NewMeeting([]int{1, 3}))
heap.Push(&pq, NewMeeting([]int{1, 2}))
fmt.Println(heap.Pop(&pq).(*Meeting)) // I would like to log this without popping prom the Queue
return 0
}
Run Code Online (Sandbox Code Playgroud)
请参阅函数中代码片段中的注释minMeetingRooms
。
我想记录优先级队列的顶部,而不实际弹出它。我怎样才能去那呢?
pop()
您可以通过返回底层数组的第一个元素来“查看”将返回的元素。(IE pq[0]
)
归档时间: |
|
查看次数: |
3100 次 |
最近记录: |