美文网首页
528.leetcode题目讲解(Python):按权重随机选择

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

作者: 夏山闻汐 | 来源:发表于2019-02-27 11:54 被阅读0次

题目如下:


题目

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




'''
@auther: Jedi.L
@Date: Wed, Feb 27, 2019 11:54
@Email: xiangyangan@gmail.com
@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):按权重随机选择

      本文链接:https://www.haomeiwen.com/subject/jhbxuqtx.html