1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
|
type Item struct { val int arrIdx int elemIdx int }
type MinHeap []Item
func (h MinHeap) Len() int { return len(h) } func (h MinHeap) Less(i, j int) bool { return h[i].val < h[j].val } func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MinHeap) Push(x interface{}) { *h = append(*h, x.(Item)) }
func (h *MinHeap) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[:n-1] return x }
func mergeKArrays(arrays [][]int) []int { k := len(arrays) if k == 0 { return nil }
h := &MinHeap{} heap.Init(h)
for i := 0; i < k; i++ { if len(arrays[i]) > 0 { heap.Push(h, Item{ val: arrays[i][0], arrIdx: i, elemIdx: 0, }) } }
var result []int for h.Len() > 0 { item := heap.Pop(h).(Item) result = append(result, item.val)
nextElemIdx := item.elemIdx + 1 if nextElemIdx < len(arrays[item.arrIdx]) { heap.Push(h, Item{ val: arrays[item.arrIdx][nextElemIdx], arrIdx: item.arrIdx, elemIdx: nextElemIdx, }) } }
return result }
func mergeKLists(lists []*ListNode) *ListNode { h := hp{} for _, head := range lists { if head != nil { h = append(h, head) } } heap.Init(&h)
dummy := &ListNode{} cur := dummy for len(h) > 0 { node := heap.Pop(&h).(*ListNode) if node.Next != nil { heap.Push(&h, node.Next) } cur.Next = node cur = cur.Next } return dummy.Next }
type hp []*ListNode func (h hp) Len() int { return len(h) } func (h hp) Less(i, j int) bool { return h[i].Val < h[j].Val } func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *hp) Push(v any) { *h = append(*h, v.(*ListNode)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
|