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]
思路:这题最关键的思路是:讲weight函数,映射成长度关系,累加函数,然后落在累加函数的数字,代表是几号index
Use accumulated freq array to get idx.
w[] = {2,5,3,4} => wsum[] = {2,7,10,14}
then get random val random.nextInt(14)+1
, idx is in range [1,14]
idx in [1,2] return 0
idx in [3,7] return 1
idx in [8,10] return 2
idx in [11,14] return 3
那么这题变成了LeetCode 35. Search Insert Position
O(N) init, O(lgN) pick;
注意:random出来的范围是[0,n-1), 需要再加1变成[1,n]
找第一个比他大的index;
class Solution {
private int[] sum;
private Random random;
private int len;
public Solution(int[] w) {
int n = w.length;
this.sum = new int[n];
sum[0] = w[0];
for(int i = 1; i < n; i++) {
sum[i] = sum[i - 1] + w[i];
}
this.random = new Random();
this.len = sum[n - 1];
}
public int pickIndex() {
int index = random.nextInt(len) + 1;
return getIndex(sum, index);
}
// w[] = {2,5,3,4} => wsum[] = {2,7,10,14}
// 找到第一个比random出来的值,大的,就是index;这样就保证了均衡;
private int getIndex(int[] sum, int index) {
int start = 0; int end = sum.length - 1;
while(start + 1 < end) {
int mid = start + (end - start) / 2;
if(sum[mid] >= index) {
end = mid;
} else {
start = mid;
}
}
if(sum[start] >= index) {
return start;
}
return end;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(w);
* int param_1 = obj.pickIndex();
*/