js按条件截取字符串
683 2023-04-03 04:47:42
堆因为其插入删除的操作时间复杂度低,因此优先队列通常是靠堆来实现的。Go的堆使用要实现heap包下的Interface接口
type Interface interface {sort.InterfacePush(x any) // add x as element Len()Pop() any // remove and return element Len() - 1.}
具体使用如下
package mainimport ("container/heap""fmt")// An MyHeap is a min-heap of ints.type people struct {name stringage int}type MyHeap []peoplefunc (h MyHeap) Len() int {return len(h)}func (h MyHeap) Less(i, j int) bool {if h[i].age == h[j].age {// 先按age从大排序,再按名字从小排序return h[i].name < h[j].name} else {return h[i].age > h[j].age}}func (h MyHeap) Swap(i, j int) {h[i], h[j] = h[j], h[i]}func (h *MyHeap) Push(x interface{}) {*h = append(*h, x.(people))}func (h *MyHeap) Pop() interface{} {res := (*h)[len(*h)-1]*h = (*h)[:len(*h)-1]return res}func main() {h := &MyHeap{people{"h", 2}, people{"h", 3}, people{"a", 1}}heap.Init(h)fmt.Printf("%v ", h) //&[{h 3} {h 2} {a 1}] heap.Push(h, people{"a", 4})fmt.Printf("%v ", h)// &[{a 4} {h 3} {a 1} {h 2}]for h.Len() > 0 {fmt.Printf("%v ", heap.Pop(h))}//{a 4} {h 3} {h 2} {a 1}}