Given an array w
of positive integers, where w[i]
describes the weight of index i
, write a function pickIndex
which randomly picks an index in proportion to its weight.
Note:
1 <= w.length <= 10000
1 <= w[i] <= 10^5
pickIndex
will be called at most10000
times.
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 array w
. pickIndex
has no arguments. Arguments are always wrapped with a list, even if there aren't any.
random函数是等概率随机,要实现有权重的随机,可以虚拟出n个点(n等于所有权重之和),每一区间的长度正比于权重,随机得到的点落在哪个区间,就相当于“随机”得到的是这个区间对应的点
可以把权重数组累加,得到累加和数组,再用binary search找random函数随机出的点落在哪个区间
注意:区间的开闭!即s[mid]==target的时候,算在下一个区间,left=mid+1
time: O(n) + O(logn), space: O(n) -- n: length of weights array
class Solution { private int[] s; Random rand = new Random(); public Solution(int[] w) { s = new int[w.length]; s[0] = w[0]; for(int i = 1; i < w.length; i++) { s[i] = s[i-1] + w[i]; } } public int pickIndex() { int target = rand.nextInt(s[s.length - 1]); int l = 0, r = s.length - 1; while(l < r) { int m = l + (r - l) / 2; if(s[m] == target) l = m + 1; else if(s[m] < target) l = m + 1; else r = m; } return l; } } /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(w); * int param_1 = obj.pickIndex(); */
ref: https://www.cnblogs.com/grandyang/p/9784690.html