dougong8012 2018-03-09 14:20
浏览 247
已采纳

从golang中的优先级队列中删除元素

I take the full realization of priority queue from golang docs. I'm interesting in removing several elements at once like heap.Remove(&queue, index1, index2, ...).

Now it can be done in the straightforward way:

for _, event := range events {
    heap.Remove(&queue, event.getIndex())
}

But this method has an overhead because every call to heap.Remove reorganizes tree. It seems more efficient if we can remove all unnecessary elements firstly and only then reorganize tree.

How it can be implemented?

  • 写回答

2条回答 默认 最新

  • drphfy1198 2018-03-09 16:26
    关注

    Since the underlying data structure of your heap is a slice, you can remove the elements directly from the slice and re-initialize the heap again after.

    Starting from your example:

    for _, event := range events {
        i := event.GetIndex()
        queue[i], queue[len(queue)-1] = queue[len(queue)-1], queue[i]
        queue = queue[:len(queue)-1]
    }
    heap.Init(&queue)
    

    And a working example: https://play.golang.org/p/-KMEilCm3t9

    func main() {
        h := IntHeap{1, 5, 2, 9, 8, 3, 7}
    
        toRemove := 8
        for i := 0; i < len(h); i++ {
            n := h[i]
            if n == toRemove {
                h[i], h[len(h)-1] = h[len(h)-1], h[i]
                h = h[:len(h)-1]
                i--
            }
        }
    
        heap.Init(&h)
        fmt.Println(h)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因