528. Random Pick with Weight
Description
Difficulty: Medium
Related Topics: Array, Math, Binary Search, Prefix Sum, Randomized
You are given a 0-indexed array of positive integers w
where w[i]
describes the weight of the ith index.
You need to implement the function pickIndex()
, which randomly picks an index in the range [0, w.length - 1]
(inclusive) and returns it. The probability of picking an index i
is w[i] / sum(w)
.
- For example, if
w = [1, 3]
, the probability of picking index0
is1 / (1 + 3) = 0.25
(i.e.,25%
), and the probability of picking index1
is3 / (1 + 3) = 0.75
(i.e.,75%
).
Example 1:
1 | Input |
Example 2:
1 | Input |
Constraints:
- 1 <= w.length <= 104
- 1 <= w[i] <= 105
pickIndex
will be called at most 104 times.
Hints/Notes
- 2023/08/12
- preSum
- binary search to find the left boundry
- if the number doesn’t exist, we can iterpret the return as
- where it ought to be in the array
- the index of value > target
- Leetcode solution(checked)
Solution
Language: C++
Cleaner solution with built in fuctions
1 | class Solution { |
1 | class Solution { |