【LeetCode】528. 按权重随机选择 解题报告 (python)

原题地址:https://leetcode-cn.com/problems/random-pick-with-weight/submissions/

题目描述:

给定一个正整数数组 w ,其中 w[i] 代表位置 i 的权重,请写一个函数 pickIndex ,它可以随机地获取位置 i,选取位置 i 的概率与 w[i] 成正比。

说明:

1 <= w.length <= 10000
1 <= w[i] <= 10^5
pickIndex 将被调用不超过 10000 次
示例1:

输入: 
["Solution","pickIndex"]
[[[1]],[]]
输出: [null,0]
示例2:

输入: 
["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"]
[[[1,3]],[],[],[],[],[]]
输出: [null,0,1,1,1,0]
输入语法说明:

输入是两个列表:调用成员函数名和调用的参数。Solution 的构造函数有一个参数,即数组 w。pickIndex 没有参数。输入参数是一个列表,即使参数为空,也会输入一个 [] 空列表。

 

解题方案:

采用python内部函数,二分法bisect:

class Solution:

    def __init__(self, w: List[int]):
        self.w = [0]
        self.sum = 0
        for i in w:
            self.sum += i
            self.w.append(self.sum)
        self.sum -= 1

    def pickIndex(self) -> int:
        w = random.randint(0, self.sum)
        return bisect.bisect(self.w, w) - 1


# Your Solution object will be instantiated and called as such:
# obj = Solution(w)
# param_1 = obj.pickIndex()
class Solution:

    def __init__(self, w: List[int]):
        self.ans, cur, total = [], 0, sum(w)
        cur = 0
        for x in w:
            cur += x 
            self.ans.append(cur/total)

    def pickIndex(self) -> int:
        return bisect.bisect(self.ans,random.random())

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值