Randomly selecting an element from a weighted list

后端 未结 5 1250
臣服心动
臣服心动 2020-12-24 15:01

I have a list of 100,000 objects. Every list element has a \"weight\" associated with it that is a positive int from 1 to N.

What is the most efficient way to select

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-24 15:17

    I really like jonderry's solution but I'm wondering if this problem needs a structure as complex as the augmented binary search tree. What if we kept two arrays, one with the input weights, say a={1,1,2,5} and one with the cumulative weights (very similar idea to jonderry's solution) which would be b={1,2,4,9}. Now generate a random number in [1 9] (say x) and binary search for it in the cumulative sum array. The location i where b[i]<=x and b[i-1]>x is noted and a[i] is returned. So, if the random number were 3, we would get i=3, and a[3]=2 would be returned. This ensures the same complexity as the augmented tree solution with an easier implementation.

提交回复
热议问题