Practice/Meta/Leetcode 528. Random Pick with Weight
CodingMust
Design a data structure that supports weighted random selection. You will be given an array of positive integers representing weights, where each weight corresponds to an element at that index. Implement a class that:
pickIndex() method that returns a random index, where the probability of returning index i is proportional to weights[i]The probability of picking index i should be exactly weights[i] / sum(weights).
For example, if weights are [1, 3], index 0 should be picked 25% of the time and index 1 should be picked 75% of the time.
pickIndex() method that returns an index based on weighted probabilitypickIndex()1 <= weights.length <= 100001 <= weights[i] <= 100000pickIndex() will be called at most 10000 timesExample 1:
` Input: weights = [1, 3] Operations: pickIndex(), pickIndex(), pickIndex(), pickIndex(), pickIndex() Output: [1, 1, 0, 1, 1] (one possible output) Explanation:
Example 2:
` Input: weights = [1, 2, 3, 4] Operations: pickIndex() called 10 times Output: [3, 2, 1, 3, 3, 2, 3, 1, 3, 2] (one possible output) Explanation:
Example 3:
Input: weights = [5] Operations: pickIndex(), pickIndex(), pickIndex() Output: [0, 0, 0] Explanation: Only one index exists, so it's always returned