duanhuang1967 2017-03-31 04:56
浏览 27
已采纳

Go的堆接口如何工作?

In Go, you can implement a heap as such: https://golang.org/src/container/heap/example_pq_test.go

You implement the sort.Interface, Pop, and Push and you've got yourself a priority queue/heap. In the example of both Pop and Push implementations the heap.Fix function isn't called. I see that heap.Init is called, so I can understand some heap-ifying happening then. However, you are able to push and pop items, which runs your own code, and the heap property is maintained.

If you push or pop items after init without calling heap.fix, how does the heap property get maintained?

Here's a playground of the example: https://play.golang.org/p/wE413xwmxE

  • 写回答

1条回答 默认 最新

  • duanchouyi6730 2017-03-31 07:24
    关注

    To keep heap implementation simple, you are only required to provide queuing logic for your custom type. Heapification is done by the heap package itself. It does so by calling the Push/Pop defined on your type, and then calling the heapification procedure:

    // from golang.org/src/container/heap/heap.go
    
    // Push pushes the element x onto the heap. The complexity is
    // O(log(n)) where n = h.Len().
    //
    func Push(h Interface, x interface{}) {
        h.Push(x)        // call to Push defined on your custom type
        up(h, h.Len()-1) // **heapification**
    }
    
    // Pop removes the minimum element (according to Less) from the heap
    // and returns it. The complexity is O(log(n)) where n = h.Len().
    // It is equivalent to Remove(h, 0).
    //
    func Pop(h Interface) interface{} {
        n := h.Len() - 1
        h.Swap(0, n)
        down(h, 0, n) // **heapification**
        return h.Pop()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图