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条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看