← 中文资源

简体中文版本

用堆合并 K 个有序切片

每个切片的首元素先入最小堆,每次弹出最小值并把该切片的下一个元素补进堆里:K 路归并只需一遍扫描完成,不需要反复比较所有切片的全部元素。

阅读英文原文

实现说明

整个示例围绕函数 Len、Less、Swap、Push组织。 在这里做循环的是 for i, s := range slices。

使用要点

  • main 按顺序串起 mergeKSorted;运行文件就会把这个流程跑一遍。

常见问题

「用堆合并 K 个有序切片」这个示例怎么运行?

文件自包含:直接运行,没有需要预先安装的依赖。

主签名形如 func (h minHeap) Len() int

核心语句

func (h minHeap) Less(i, j int) bool { return h[i].value < h[j].value }
func (h *minHeap) Push(v any)        { *h = append(*h, v.(item)) }
func (h minHeap) Len() int           { return len(h) }

代码示例

package main

import (
	"container/heap"
	"fmt"
)

// item pairs a value with the index of the sorted slice it came from
type item struct {
	value int
	src   int
}

type minHeap []item

func (h minHeap) Len() int           { return len(h) }
func (h minHeap) Less(i, j int) bool { return h[i].value < h[j].value }
func (h minHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *minHeap) Push(v any)        { *h = append(*h, v.(item)) }
func (h *minHeap) Pop() any {
	old := *h
	n := len(old)
	v := old[n-1]
	*h = old[:n-1]
	return v
}

// mergeKSorted: one head per slice in the heap, always pop the smallest
func mergeKSorted(slices [][]int) []int {
	h := &minHeap{}
	for i, s := range slices {
		if len(s) > 0 {
			*h = append(*h, item{value: s[0], src: i})
		}
	}
	heap.Init(h)
	pos := make([]int, len(slices))
	var merged []int
	for h.Len() > 0 {
		it := heap.Pop(h).(item)
		merged = append(merged, it.value)
		pos[it.src]++
		if pos[it.src] < len(slices[it.src]) {
			heap.Push(h, item{value: slices[it.src][pos[it.src]], src: it.src})
		}
	}
	return merged
}

func main() {
	fmt.Println(mergeKSorted([][]int{{1, 4, 7}, {2, 5, 8}, {3, 6, 9}}))
	fmt.Println(mergeKSorted([][]int{{}, {1}, {0, 2}}))
}