编程语言
首页 > 编程语言> > 【LeetCode】528. 按权重随机选择 解题报告 (python)

【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())

 

暮雨凉初透 发布了272 篇原创文章 · 获赞 15 · 访问量 5万+ 私信 关注

标签:__,python,self,pickIndex,Solution,bisect,sum,528,LeetCode
来源: https://blog.csdn.net/qq_32805671/article/details/103991811