1. 程式人生 > >528. Random Pick with Weight - Medium

528. 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 wpickIndex has no arguments. Arguments are always wrapped with a list, even if there aren't any.

 

random函式是等概率隨機,要實現有權重的隨機,可以虛擬出n個點(n等於所有權重之和),每一區間的長度正比於權重,隨機得到的點落在哪個區間,就相當於“隨機”得到的是這個區間對應的點

可以把權重陣列累加,得到累加和陣列,再用binary search找random函式隨機出的點落在哪個區間

注意:區間的開閉!即s[mid]==target的時候,算在下一個區間,left=mid+1

time: O(n) + O(logn), space: O(n) -- n: length of weights array

class Solution {
    private int[] s;
    Random rand = new Random();

    public Solution(int[] w) {
        s = new int[w.length];
        s[0] = w[0];
        for(int i = 1; i < w.length; i++) {
            s[i] = s[i-1] + w[i];
        }
    }
    
    public int pickIndex() {
        int target = rand.nextInt(s[s.length - 1]);
        int l = 0, r = s.length - 1;
        while(l < r) {
            int m = l + (r - l) / 2;
            if(s[m] == target)
                l = m + 1;
            else if(s[m] < target)
                l = m + 1;
            else
                r = m;
        }
        return l;
    }
}

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

 

 

 

 

ref: https://www.cnblogs.com/grandyang/p/9784690.html