|
| 1 | +### Question {#question} |
| 2 | + |
| 3 | +[https://leetcode.com/problems/random-pick-with-weight/description/](https://leetcode.com/problems/random-pick-with-weight/description/) |
| 4 | + |
| 5 | +Given an array w of positive integers, where w\[i\] describes the weight of index i, write a function pickIndex which randomly picks an index in proportion to its weight. |
| 6 | + |
| 7 | +**Note: |
| 8 | +** |
| 9 | + |
| 10 | +1. 1 <= w.length <= 10000 |
| 11 | +2. 1 <= w\[i\] <= 10^5 |
| 12 | +3. pickIndex will be called at most 10000 times. |
| 13 | + |
| 14 | +**Example 1:** |
| 15 | + |
| 16 | +``` |
| 17 | +Input: |
| 18 | +["Solution","pickIndex"] |
| 19 | +[[[1]],[]] |
| 20 | +Output: [null,0] |
| 21 | +``` |
| 22 | + |
| 23 | +**Example 2:** |
| 24 | + |
| 25 | +``` |
| 26 | +Input: |
| 27 | +["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"] |
| 28 | +[[[1,3]],[],[],[],[],[]] |
| 29 | +Output: [null,0,1,1,1,0] |
| 30 | +``` |
| 31 | + |
| 32 | +**Explanation of Input Syntax: |
| 33 | +** |
| 34 | + |
| 35 | +The input is two lists: the subroutines called and their arguments. Solution's constructor has one argument, the array w. pickIndex has no arguments. Arguments are always wrapped with a list, even if there aren't any. |
| 36 | + |
| 37 | +### Thought Process {#thought-process} |
| 38 | + |
| 39 | +1. Binary Search |
| 40 | + 1. Since every integer is weighted, we need to get the total sum before we pick a point |
| 41 | + 2. The total sum does not exceed the integer max value, so we can use a int to store the sum |
| 42 | + 3. After creating accumulated sum array, we generate a random point, r, between \[0, sum\) and perform binary search on this accumulated array |
| 43 | + 4. Time complexity O\(n\) |
| 44 | + 5. Space complexity O\(n\) |
| 45 | +2. TreeMap |
| 46 | + 1. |
| 47 | +3. asd |
| 48 | + |
| 49 | +### Solution |
| 50 | + |
| 51 | +```java |
| 52 | +class Solution { |
| 53 | + private int[] presum; |
| 54 | + private int n; |
| 55 | + private Random rand; |
| 56 | + |
| 57 | + public Solution(int[] w) { |
| 58 | + n = w.length; |
| 59 | + presum = new int[n]; |
| 60 | + rand = new Random(); |
| 61 | + presum[0] = w[0]; |
| 62 | + for (int i = 1; i < n; i++) presum[i] = presum[i - 1] + w[i]; |
| 63 | + } |
| 64 | + |
| 65 | + public int pickIndex() { |
| 66 | + int r = rand.nextInt(presum[n - 1]) + 1; |
| 67 | + int i = Arrays.binarySearch(presum, r); |
| 68 | + if (i < 0) i = -(i + 1); |
| 69 | + return i; |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +/** |
| 74 | + * Your Solution object will be instantiated and called as such: |
| 75 | + * Solution obj = new Solution(w); |
| 76 | + * int param_1 = obj.pickIndex(); |
| 77 | + */ |
| 78 | +``` |
| 79 | + |
| 80 | +### Additional {#additional} |
| 81 | + |
| 82 | + |
| 83 | + |
0 commit comments