gitee.com/KyleChenSource/lib-robot@v1.0.2/robottest/common/container/heap.go (about) 1 // 实现一个整数队 heap.Interface,可以使用container/heap进行操作 2 package container 3 4 // IntHeap 是一个由整数组成的最小堆。 5 type IntHeap []int 6 7 func (h IntHeap) Len() int { return len(h) } 8 func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } 9 func (h IntHeap) Swap(i, j int) { temp := h[i]; h[i] = h[j]; h[j] = temp } 10 11 func (h *IntHeap) Push(x interface{}) { 12 // Push 和 Pop 使用 pointer receiver 作为参数, 13 // 因为它们不仅会对切片的内容进行调整,还会修改切片的长度。 14 *h = append(*h, x.(int)) 15 } 16 17 func (h *IntHeap) Pop() interface{} { 18 old := *h 19 n := len(old) 20 x := old[n-1] 21 *h = old[0 : n-1] 22 return x 23 } 24 25 func (h *IntHeap) Front() int { 26 return (*h)[0] 27 } 28 29 type IntHeap64 []int64 30 31 func (h IntHeap64) Len() int { return len(h) } 32 func (h IntHeap64) Less(i, j int) bool { return h[i] < h[j] } 33 func (h IntHeap64) Swap(i, j int) { temp := h[i]; h[i] = h[j]; h[j] = temp } 34 35 func (h *IntHeap64) Push(x interface{}) { 36 // Push 和 Pop 使用 pointer receiver 作为参数, 37 // 因为它们不仅会对切片的内容进行调整,还会修改切片的长度。 38 *h = append(*h, x.(int64)) 39 } 40 41 func (h *IntHeap64) Pop() interface{} { 42 old := *h 43 n := len(old) 44 x := old[n-1] 45 *h = old[0 : n-1] 46 return x 47 } 48 49 func (h *IntHeap64) Front() int64 { 50 return (*h)[0] 51 }