我要讓整數的最小和最大堆:使兩個結構與一個方法不同實現
package main
import (
"container/heap"
"fmt"
)
func main() {
hi := make(IntHeap, 0)
for number := 10; number >= 0; number-- {
hi = append(hi, number)
}
heap.Init(&hi)
fmt.Println(heap.Pop(&hi))
fmt.Println(heap.Pop(&hi))
fmt.Println(heap.Pop(&hi))
}
// An IntHeap is a min-heap of ints.
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
}
type IntMaxHeap IntHeap
func (h IntMaxHeap) Less(i, j int) bool { return h[i] > h[j] }
如果我想使用IntMaxHeap
相反,我得到:
./median_stream.go:14: cannot use &hi (type *IntMaxHeap) as type heap.Interface in function argument:
*IntMaxHeap does not implement heap.Interface (missing Len method)
./median_stream.go:15: cannot use &hi (type *IntMaxHeap) as type heap.Interface in function argument:
*IntMaxHeap does not implement heap.Interface (missing Len method)
./median_stream.go:16: cannot use &hi (type *IntMaxHeap) as type heap.Interface in function argument:
*IntMaxHeap does not implement heap.Interface (missing Len method)
./median_stream.go:17: cannot use &hi (type *IntMaxHeap) as type heap.Interface in function argument:
*IntMaxHeap does not implement heap.Interface (missing Len method)
我怎樣才能製作兩個結構(「類」),這些結構與僅僅一個方法實現有所不同?工作版本應該從堆中打印3個最大的數字。