Top K Streaming With A Bounded Heap

Keep the K largest values from an unbounded stream using a min-heap that evicts its smallest element whenever the bound is exceeded.

GoData Integrity

Code

gosnippet
45 lines
package main

import (
	"container/heap"
	"fmt"
)

// min-heap:堆顶是当前最小,超出容量时先淘汰它
type minHeap []int

func (h minHeap) Len() int            { return len(h) }
func (h minHeap) Less(i, j int) bool  { return h[i] < h[j] }
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.(int)) }
func (h *minHeap) Pop() any {
	old := *h
	n := len(old)
	v := old[n-1]
	*h = old[:n-1]
	return v
}

func topK(stream []int, k int) []int {
	h := &minHeap{}
	heap.Init(h)
	for _, v := range stream {
		heap.Push(h, v)
		if h.Len() > k {
			heap.Pop(h) // 丢弃当前最小,堆里始终是至今最大的 k 个
		}
	}
	out := make([]int, 0, h.Len())
	for h.Len() > 0 {
		out = append(out, heap.Pop(h).(int))
	}
	// Pop 产出升序(最小在前),反转成降序排名
	for i, j := 0, len(out)-1; i < j; i, j = i+1, j-1 {
		out[i], out[j] = out[j], out[i]
	}
	return out
}

func main() {
	fmt.Println(topK([]int{4, 9, 1, 7, 12, 3, 8}, 3))
}

How the snippet works

The snippet is organized around the functions Len, Less, Swap and Push.

A single loop drives the file — for _, v := range stream.

Watch out for

  • Zero packages pulled in — the runtime ships every API this code touches.

Putting it to use

Entry signature: func (h minHeap) Len() int

main sequences topK; executing the file runs that flow once.

Core lines

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

Interactive Tools for This Topic

FAQ

How do you run Top K Streaming With A Bounded Heap?
This is a complete program, not a library excerpt — execution starts at the top.