528. Random Pick with Weight
https://leetcode.com/problems/random-pick-with-weight/
import random
class Solution:
def __init__(self, w: List[int]):
self.nums = []
for i,weight in enumerate(w):
for _ in range(weight):
self.nums.append(i)
def pickIndex(self) -> int:
randIndex = random.randint(0,len(self.nums)-1)
return self.nums[randIndex]
w = [1,2,3,4]
presumW= [1,3,6,10]
if random index in
0 - 1 ====> 0
1 - 3 ====> 1
3 - 6 ====> 2
6 - 10 ===> 3Last updated