蓄水池抽样算法golang版本
2023-08-20
1分钟阅读时长
蓄水池抽样算法
func reservoirSample(k int, data []int) []int {
n := len(data)
reservoir := make([]int, k)
for i := 0; i < k; i++ {
reservoir[i] = data[i]
}
for i := k; i < n; i++ {
j := rand.Intn(i + 1)
if j < k {
reservoir[j] = data[i]
}
}
return reservoir
}