|
| 1 | +""" |
| 2 | +Medium |
| 3 | +## Questions |
| 4 | +### [528. Random Pick with Weight](https://leetcode.com/problems/random-pick-with-weight/) |
| 5 | +
|
| 6 | +Given an array w of positive integers, where w[i] describes the weight of index i, write a function pickIndex which |
| 7 | +randomly picks an index in proportion to its weight. |
| 8 | +
|
| 9 | +Note: |
| 10 | +1 <= w.length <= 10000 |
| 11 | +1 <= w[i] <= 10^5 |
| 12 | +pickIndex will be called at most 10000 times. |
| 13 | +
|
| 14 | +Example 1: |
| 15 | +Input: |
| 16 | +["Solution","pickIndex"] |
| 17 | +[[[1]],[]] |
| 18 | +Output: [null,0] |
| 19 | +
|
| 20 | +Example 2: |
| 21 | +Input: |
| 22 | +["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"] |
| 23 | +[[[1,3]],[],[],[],[],[]] |
| 24 | +Output: [null,0,1,1,1,0] |
| 25 | +
|
| 26 | +Explanation of Input Syntax: |
| 27 | +The input is two lists: the subroutines called and their arguments. Solution's constructor has one argument, |
| 28 | +the array w. pickIndex has no arguments. Arguments are always wrapped with a list, even if there aren't any. |
| 29 | +""" |
| 30 | + |
| 31 | + |
| 32 | +# Solutions |
| 33 | + |
| 34 | + |
| 35 | +class Solution: |
| 36 | + def __init__(self, w: List[int]): |
| 37 | + self.prefix_sum = list(itertools.accumulate(w)) |
| 38 | + |
| 39 | + def pickIndex(self) -> int: |
| 40 | + if not self.prefix_sum: |
| 41 | + return 0 |
| 42 | + rand = random.randint(0, self.prefix_sum[-1] - 1) |
| 43 | + return bisect.bisect_right(self.prefix_sum, rand) |
| 44 | + |
| 45 | + |
| 46 | +# Your Solution object will be instantiated and called as such: |
| 47 | +# obj = Solution(w) |
| 48 | +# param_1 = obj.pickIndex() |
| 49 | + |
| 50 | + |
| 51 | +# Runtime: 232 ms, faster than 91.15% of Python3 online submissions |
| 52 | +# Memory Usage: 18.2 MB, less than 81.65% of Python3 online submissions |
0 commit comments