Leetcode 528. Random Pick with Weight
题目
解法:brutal force
把每个ind按照相应权重的数量扩充,比如[1,3]扩充成[0,0,1,1,1],然后从中随机选取一个值返回。这样是TLE的,因为时间复杂度会是O(sum(weight)),不过这是最直观的
python代码如下:
class Solution:
def __init__(self, w: List[int]):
new_w = []
for ind,w_ in enumerate(w):
new_w += [ind]*w_
self.new_w = new_w
def pickIndex(self) -> int:
ind = random.randrange(0,len(self.new_w))
return self.new_w[ind]
解法2:前缀和+线性搜索
class Solution {
vector<int> prefix_sum;
public:
Solution(vector<