|
| 1 | +<p>You are given a <strong>0-indexed</strong> array of positive integers <code>w</code> where <code>w[i]</code> describes the <strong>weight</strong> of the <code>i<sup>th</sup></code> index.</p> |
| 2 | + |
| 3 | +<p>You need to implement the function <code>pickIndex()</code>, which <strong>randomly</strong> picks an index in the range <code>[0, w.length - 1]</code> (<strong>inclusive</strong>) and returns it. The <strong>probability</strong> of picking an index <code>i</code> is <code>w[i] / sum(w)</code>.</p> |
| 4 | + |
| 5 | +<ul> |
| 6 | + <li>For example, if <code>w = [1, 3]</code>, the probability of picking index <code>0</code> is <code>1 / (1 + 3) = 0.25</code> (i.e., <code>25%</code>), and the probability of picking index <code>1</code> is <code>3 / (1 + 3) = 0.75</code> (i.e., <code>75%</code>).</li> |
| 7 | +</ul> |
| 8 | + |
| 9 | +<p> </p> |
| 10 | +<p><strong class="example">Example 1:</strong></p> |
| 11 | + |
| 12 | +<pre> |
| 13 | +<strong>Input</strong> |
| 14 | +["Solution","pickIndex"] |
| 15 | +[[[1]],[]] |
| 16 | +<strong>Output</strong> |
| 17 | +[null,0] |
| 18 | + |
| 19 | +<strong>Explanation</strong> |
| 20 | +Solution solution = new Solution([1]); |
| 21 | +solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w. |
| 22 | +</pre> |
| 23 | + |
| 24 | +<p><strong class="example">Example 2:</strong></p> |
| 25 | + |
| 26 | +<pre> |
| 27 | +<strong>Input</strong> |
| 28 | +["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"] |
| 29 | +[[[1,3]],[],[],[],[],[]] |
| 30 | +<strong>Output</strong> |
| 31 | +[null,1,1,1,1,0] |
| 32 | + |
| 33 | +<strong>Explanation</strong> |
| 34 | +Solution solution = new Solution([1, 3]); |
| 35 | +solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4. |
| 36 | +solution.pickIndex(); // return 1 |
| 37 | +solution.pickIndex(); // return 1 |
| 38 | +solution.pickIndex(); // return 1 |
| 39 | +solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4. |
| 40 | + |
| 41 | +Since this is a randomization problem, multiple answers are allowed. |
| 42 | +All of the following outputs can be considered correct: |
| 43 | +[null,1,1,1,1,0] |
| 44 | +[null,1,1,1,1,1] |
| 45 | +[null,1,1,1,0,0] |
| 46 | +[null,1,1,1,0,1] |
| 47 | +[null,1,0,1,0,0] |
| 48 | +...... |
| 49 | +and so on. |
| 50 | +</pre> |
| 51 | + |
| 52 | +<p> </p> |
| 53 | +<p><strong>Constraints:</strong></p> |
| 54 | + |
| 55 | +<ul> |
| 56 | + <li><code>1 <= w.length <= 10<sup>4</sup></code></li> |
| 57 | + <li><code>1 <= w[i] <= 10<sup>5</sup></code></li> |
| 58 | + <li><code>pickIndex</code> will be called at most <code>10<sup>4</sup></code> times.</li> |
| 59 | +</ul> |
0 commit comments