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]

class Solution {
    private int[] accw;
    public Solution(int[] w) {
        this.accw = new int[w.length];
        for(int i = 0; i < w.length; i++) {
            accw[i] = w[i];
            if(i >= 1) {
                accw[i] += accw[i - 1];
            }
        }
    }
    
    public int pickIndex() {
        Random random = new Random();
        //注意这里是nextInt(n) + 1, 因为weight是从1开始的,而且nextInt(n) => [0, n -1) + 1之后,[1,n];
        int index = random.nextInt(accw[accw.length - 1]) + 1; 
        return binarySearch(index, accw);
    }
    
    private int binarySearch(int target, int[] A) {
        int start = 0; int end = A.length - 1;
        while(start + 1 < end) {
            int mid = start + (end - start) / 2;
            if(A[mid] == target) {
                return mid;
            } else if(A[mid] < target) {
                start = mid;
            } else {
                // target < A[mid];
                end = mid;
            }
        }
        
        if(target <= A[start]) {
            return start;
        } 
        return end;
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(w);
 * int param_1 = obj.pickIndex();
 */
发布了710 篇原创文章 · 获赞 13 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/u013325815/article/details/105657001
今日推荐