Random Pick with Weight
medium 原题链接:https://leetcode.com/problems/random-pick-with-weight/
最后更新于
这有帮助吗?
medium 原题链接:https://leetcode.com/problems/random-pick-with-weight/
最后更新于
这有帮助吗?
原题链接:
You are given an array of positive integers
w
wherew[i]
describes the weight ofith
index (0-indexed).We need to call the function
pickIndex()
which randomly returns an integer in the range[0, w.length - 1]
.pickIndex()
should return the integer proportional to its weight in thew
array. For example, forw = [1, 3]
, the probability of picking the index0
is1 / (1 + 3) = 0.25
(i.e 25%) while the probability of picking the index1
is3 / (1 + 3) = 0.75
(i.e 75%).More formally, the probability of picking index
i
isw[i] / sum(w)
.
Input :
["Solution","pickIndex"]
[[[1]],[]]
Output :
[null,0]
Explanation :
Solution solution = new Solution([1]);
solution.pickIndex();
// return 0. Since there is only one single element on the array the only option is to return the first element.
the array of {1, 3, 4, 6}
the pickIndex() call will have
1/(1+3+4+6) = 1/14 = ~7% chance of picking index 0;
3/14 = 21% change of picking index 1;
4/14 = 29% change of picking index 2;
and 6/14 = 43% of picking index 3.
binary search