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. 1 <= w.length <= 10000
  2. 1 <= w[i] <= 10^5
  3. pickIndex will be called at most 10000 times.

Example 1:

Input: 
["Solution","pickIndex"]
[[[1]],[]]
Output: [null,0]

Example 2:

Input: 
["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"]
[[[1,3]],[],[],[],[],[]]
Output: [null,0,1,1,1,0]

思路:这题最关键的思路是:讲weight函数,映射成长度关系,累加函数,然后落在累加函数的数字,代表是几号index

Use accumulated freq array to get idx.
w[] = {2,5,3,4} => wsum[] = {2,7,10,14}
then get random val random.nextInt(14)+1, idx is in range [1,14]

idx in [1,2] return 0
idx in [3,7] return 1
idx in [8,10] return 2
idx in [11,14] return 3

那么这题变成了LeetCode 35. Search Insert Position

O(N) init, O(lgN) pick;

 注意:random出来的范围是[0,n-1), 需要再加1变成[1,n]

找第一个比他大的index;

class Solution {
    private int[] sum;
    private Random random;
    private int len;
    public Solution(int[] w) {
        int n = w.length;
        this.sum = new int[n];
        sum[0] = w[0];
        for(int i = 1; i < n; i++) {
            sum[i] = sum[i - 1] + w[i];
        }
        this.random = new Random();
        this.len = sum[n - 1];
    }
    
    public int pickIndex() {
        int index = random.nextInt(len) + 1;
        return getIndex(sum, index);
    }
    
    // w[] = {2,5,3,4} => wsum[] = {2,7,10,14}
    // 找到第一个比random出来的值,大的,就是index;这样就保证了均衡;
    private int getIndex(int[] sum, int index) {
        int start = 0; int end = sum.length - 1;
        while(start + 1 < end) {
            int mid = start + (end - start) / 2;
            if(sum[mid] >= index) {
                end = mid;
            } else {
                start = mid;
            }
        }
        
        if(sum[start] >= index) {
            return start;
        }
        return end;
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(w);
 * int param_1 = obj.pickIndex();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值