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 most 10000 times.
Example 1:
Input:
[“Solution”,“pickIndex”,“pickIndex”,“pickIndex”,“pickIndex”,“pickIndex”]
[[[1,3]],[],[],[],[],[]]
Output: [null,0,1,1,1,0]
第一次做random题有点懵,此题的关键之一在于清楚random的用法
random.nextInt(n) 生成的数是[0,n)之间的一个数,包含0但不包含n
按权重来生成随机数,这题是个常见的做法
先求prefix sum
比如 w[] 是 1 10 1000
prefix 1 11 1011
那么[1] [2-11] [12-1011] 三个区间里分别有1, 10, 1000个数
如果对[1, 1012)这个区间求个随机数,就可以按我们要求的权重
因为random.nextInt是从0开始的,所以我先按[0, 1011) 求了个数,再加1
private int[] prefix;
private Random rand;
public Solution(int[] w) {
rand = new Random();
prefix = new int[w.length];
for(int i= 0; i< w.length;i++) {
prefix[i] = w[i] + (i == 0 ? 0 : prefix[i-1]);
}
}
public int pickIndex() {
int cur = rand.nextInt(prefix[prefix.length-1]);
int idx = Arrays.binarySearch(prefix, cur+1);
return idx >=0 ? idx : -idx-1;
}