Randomly selecting an element from a weighted list

后端 未结 5 1214
臣服心动
臣服心动 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:35

    You can use an augmented binary search tree to store the elements, along with the sum of the weights in each subtree. This lets you insert and delete elements and weights however you want. Both sampling and updates require O(lg n) time per operation, and space usage is O(n).

    Sampling is accomplished by generating a random integer in [1, S], where S is the sum of all weights (S is stored at the root of the tree), and performing binary search using the weight-sums stored for each subtree.

提交回复
热议问题