528 Random Pick with Weight

1. Question

Given an arraywof positive integers, wherew[i]describes the weight of indexi, write a functionpickIndex which randomly picks an index in proportion to its weight.

Note:

  1. 1 <= w.length <= 10000

  2. 1 <= w[i] <= 10^5

  3. pickIndexwill be called at most10000times.

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]

2. Implementation

(1) TreeMap

(2) Binary Search

3. Time & Space Complexity

(1) TreeMap: Time: constructor: O(n), pickIndex: O(logn), Space: O(n)

(2) Binary Tree: Time: constructor: O(n), pickIndex: O(logn), Space: O(n)

Last updated

Was this helpful?