首页 > 解决方案 > 在 Go 中查看优先级队列的顶部?

问题描述

我正在尝试使用heapPush实现一个示例程序,并且我能够 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
}

请查看minMeetingRooms函数中代码片段中的注释。

我想记录优先队列的顶部,而不是实际弹出它。我怎么能这样?

标签: goheappriority-queue

解决方案


您可以通过返回底层数组的第一个元素来“窥视”pop()将返回的元素。


推荐阅读