题目:
有N个长度不一的数组,所有的数组都是有序的,请从大到小打印这N个数组整体最大的前K个数。
例如,输入含有N行元素的二维数组可以代表N个一维数组。
219, 405, 538, 845, 971
148, 558
52, 99, 348, 691
再输入整数k=5, 则打印:
Top 5: 971, 845, 691, 558, 538
package main
import (
"container/heap"
"fmt"
"errors"
)
type HeapNode struct {
value int32 //值是什么
arrNum int //来自哪个数组
index int //来自数组的哪个位置
}
type ArrayHeap []*HeapNode
func (arrayheap ArrayHeap) Len() int {
return len(arrayheap)
}
func (arrayheap ArrayHeap) Less(i, j int) bool {
return arrayheap[i].value > arrayheap[j].value //大根堆
}
func (arrayheap ArrayHeap) Swap(i, j int) {
arrayheap[i], arrayheap[j] = arrayheap[j], arrayheap[i]
}
func (arrayheap *ArrayHeap) Push(node interface{}) {
// n := len(*arrayheap)
item := node.(*HeapNode)
*arrayheap = append(*arrayheap, item)
}
func (arrayheap *ArrayHeap) Pop() interface{} {
old := *arrayheap
n := len(old)
item := old[n-1]
*arrayheap = old[0 : n-1]
return item
}
func (arrayheap *ArrayHeap) IsEmpty() bool {
length := len(*arrayheap)
return length == 0
}
func getMatriValue(matrix *[3][5]int32, i, j int) (value int32, err error) {
if i < 0 || i > len(*matrix)-1 {
return 0, errors.New("out of matrix index")
}
if j < 0 || j > len(matrix[0])-1 {
return 0, errors.New("out of matrix index")
}
return matrix[i][j], nil
}
// func printTopK( int topK) {
// }
func main() {
var matrix = [3][5]int32 {
{219, 405, 538, 845, 971},
{148, 558, 0, 0, 0},
{52, 99, 348, 691, 0},
}
myHeap := make(ArrayHeap, 0)
heap.Init(&myHeap)
heap.Push(&myHeap, &HeapNode{
value: 971,
arrNum: 0,
index: 6,
})
heap.Push(&myHeap, &HeapNode{
value: 558,
arrNum: 1,
index: 1,
})
heap.Push(&myHeap, &HeapNode{
value: 691,
arrNum: 2,
index: 3,
})
for i := 0; i < 5; i++ {
if bEmpty := myHeap.IsEmpty(); bEmpty {
break
}
item := heap.Pop(&myHeap).(*HeapNode)
fmt.Printf("value = %d, arrNum = %d, index = %d\n", item.value, item.arrNum, item.index)
if nextValue, ok := getMatriValue(&matrix, item.arrNum, item.index-1); ok == nil {
heap.Push(&myHeap, &HeapNode{
value: nextValue,
arrNum: item.arrNum,
index: item.index-1,
})
length := len(myHeap)
heap.Fix(&myHeap, length-1)
}
}
}
打印出前5个:
value = 971, arrNum = 0, index = 6
value = 691, arrNum = 2, index = 3
value = 558, arrNum = 1, index = 1
value = 348, arrNum = 2, index = 2
value = 148, arrNum = 1, index = 0
可以将原来的main函数中的代码抽取出来,单独放在printTopK函数中,打印出topK。今天先到这里,大家可以帮忙一起完善这个函数。
参考:Go标准容器之Heap
4617



被折叠的 条评论
为什么被折叠?



