leetcode528 - Random Pick with Weight - medium

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]
Explanation of Input Syntax:
The input is two lists: the subroutines called and their arguments. Solution's constructor has one argument, the array w. pickIndex has no arguments. Arguments are always wrapped with a list, even if there aren't any.
 
 
前缀和数组。
比如[1,10,1000],先生成前缀和数组[1,11,1011]。那么如果我用1011的上限生成一个[0, 1011)的随机数字,那么我规定[0, 1)的数字归1管,[1, 11)的数字归10管,[11, 1011)的数字归1000管,那就ok了。
那其实生成随机数字target后,你用binary search找到“第一个>target的数字的下标”,就是我们的答案了。 
 
实现:
class Solution {
    
    private int[] sum;
    private Random rd;
    private int total;
    public Solution(int[] w) {
        rd = new Random();
        sum = new int[w.length];
        total = 0;
        for (int i = 0; i < sum.length; i++) {
            total += w[i];
            sum[i] = total;
        }
    }
    
    public int pickIndex() {
    // target- 0~sum[last] - 1
    // find the index where sum[index] is the first number > target
        int target = rd.nextInt(sum[sum.length - 1]);
        int i = 0, j = sum.length - 1;
        while (i < j) {
            int mid = (i + j) / 2;
            if (sum[mid] <= target) {
                i = mid + 1;
            } else if (sum[mid] > target) {
                j = mid;
            }
        }
        return i;
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(w);
 * int param_1 = obj.pickIndex();
 */

 

posted @ 2018-10-04 11:18  jasminemzy  阅读(521)  评论(0编辑  收藏  举报