golang实现优先队列,解决编译依赖的问题
package main
import (
"container/heap"
"fmt"
)
type IntHeap []int
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } // 大顶堆,返回值决定是否交换元素
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) {
*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
func compileSeq(input []int) string {
// write code here
data := IntHeap{}
for i := 0; i < 5; i++ {
data = append(data, input[i])
}
heap.Init(&data)
fmt.Println(data)
for i := 5; i < len(input); i++ {
heap.Push(&data, input[i])
heap.Pop(&data)
fmt.Println(data)
}
data[3] = 1
fmt.Println(data)
heap.Fix(&data, 3)
fmt.Println(data)
return "out"
}