英文:
Is there a more generic way to implement 2 kinds of Heap (Max and Min) in Go Lang
问题
目前,Go语言文档中的示例代码如下:
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{}) {
// Push and Pop use pointer receivers because they modify the slice's length,
// not just its contents.
*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
}
我真的不想重复创建一组用于最小堆的方法和另一组用于最大堆的方法。有没有更好的方法?
英文:
Currently, the example on Go lang doc is like this:
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{}) {
// Push and Pop use pointer receivers because they modify the slice's length,
// not just its contents.
*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
}
I really don't want to repeat myself creating a set of methods for Min Heap and another set of methods for Max Heap. Is there a better way?
答案1
得分: 18
你可以使用嵌入来从你的最小堆创建一个最大堆,代码如下:
type MaxHeap struct {
IntHeap
}
func (h MaxHeap) Less(i, j int) bool { return h.IntHeap[i] > h.IntHeap[j] }
你可以在这个playground链接中找到一个可运行的示例。
英文:
You can create a max heap from your min heap using embedding, like this
type MaxHeap struct {
IntHeap
}
func (h MaxHeap) Less(i, j int) bool { return h.IntHeap[i] > h.IntHeap[j] }
See the playground for a working example.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论