Random Pick with Weight
Given an arraywof positive integers, wherew[i]describes the weight of indexi, write a functionpickIndex which randomly picks an index in proportion to its weight.
Note:
1 <= w.length <= 100001 <= w[i] <= 10^5pickIndexwill be called at most10000times.
Example
Example 1:
Input:
["Solution","pickIndex"]
[[[1]],[]]
Output:
[null,0]Example 2:
Input:
["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"]
[[[1,3]],[],[],[],[],[]]
Output:
[null,0,1,1,1,0]Explanation of Input Syntax:
The input is two lists: the subroutines called and their arguments. Solution's constructor has one argument, the arrayw.pickIndexhas no arguments. Arguments are always wrapped with a list, even if there aren't any.
Note
Use accumulated freq array to get idx.
w[] = {2,5,3,4} => wsum[] = {2,7,10,14}
then get random valrandom.nextInt(14)+1, idx is in range[1,14]
then become LeetCode 35. Search Insert Position
Time:O(n)to init,O(logn)for one pick
Space:O(n)
Code
Last updated