代码
- 计算前缀和,前缀和自带的当前值与上一个值的区间从而来表示权重
- 例如:
- 然后使用 rand.Intn 和 sort.SearchInts 来进行生成随机数和判断随机数应该插入哪个位置,即落入前缀和的哪个区间
type Solution struct {
pre []int
}
func Constructor(w []int) Solution {
n := len(w)
for i := 1; i < n; i++ {
w[i] += w[i-1]
}
return Solution{w}
}
func (this *Solution) PickIndex() int {
x := rand.Intn(this.pre[len(this.pre)-1])+1
return sort.SearchInts(this.pre, x)
}