晨哥Leetcode 528. Random Pick with Weight

Given an array w of positive integers, where w[i] describes the weight of index i, write a function pickIndex which randomly picks an index in proportion to its weight.
Note:
1 <= w.length <= 10000
1 <= w[i] <= 10^5
pickIndex will be called at most 10000 times.
Example 1:
Input:
[“Solution”,“pickIndex”,“pickIndex”,“pickIndex”,“pickIndex”,“pickIndex”]
[[[1,3]],[],[],[],[],[]]
Output: [null,0,1,1,1,0]

第一次做random题有点懵,此题的关键之一在于清楚random的用法
random.nextInt(n) 生成的数是[0,n)之间的一个数,包含0但不包含n
按权重来生成随机数,这题是个常见的做法
先求prefix sum
比如 w[] 是 1 10 1000
prefix 1 11 1011
那么[1] [2-11] [12-1011] 三个区间里分别有1, 10, 1000个数
如果对[1, 1012)这个区间求个随机数,就可以按我们要求的权重
因为random.nextInt是从0开始的,所以我先按[0, 1011) 求了个数,再加1

private int[] prefix;
    private Random rand;
    public Solution(int[] w) {
        rand = new Random();
        prefix = new int[w.length];
        for(int i= 0; i< w.length;i++) {
            prefix[i] = w[i] + (i == 0 ? 0 : prefix[i-1]);
        }
    }
    
    public int pickIndex() {
        int cur = rand.nextInt(prefix[prefix.length-1]);
        int idx = Arrays.binarySearch(prefix, cur+1);
        return idx >=0 ? idx : -idx-1;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值