528.leetcode题目讲解(Python):按权重随机选择(Random Pick with Weight)

题目如下:


528.leetcode题目讲解(Python):按权重随机选择(Random Pick with Weight)_第1张图片
题目

有了497的解题基础,这道题还是比较好解,使用bisect.bisect_left()来通过权重对元素进行定位。参考代码如下:




'''
@auther: Jedi.L
@Date: Wed, Feb 27, 2019 11:54
@Email: [email protected]
@Blog: www.tundrazone.com
'''

import random
import bisect


class Solution:
    def __init__(self, w: List[int]):
        self.w = w
        self.sw = []
        w_sum = 0

        for ww in self.w:
            w_sum += ww
            self.sw.append(w_sum)

    def pickIndex(self) -> int:
        return bisect.bisect_left(
            self.sw, random.randint(1, self.sw[-1]))


源码地址:
https://github.com/jediL/LeetCodeByPython

其它题目:[leetcode题目答案讲解汇总(Python版 持续更新)]
(https://www.jianshu.com/p/60b5241ca28e)

ps:如果您有好的建议,欢迎交流 :-D,
也欢迎访问我的个人博客 苔原带 (www.tundrazone.com)

你可能感兴趣的:(528.leetcode题目讲解(Python):按权重随机选择(Random Pick with Weight))