zoukankan      html  css  js  c++  java
  • 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. 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

  • 相关阅读:
    如何快速实现一个command
    引用mvvmlight dll ,操作command
    ANSI X9.8标准 PIN xor PAN获取PIN BlOCK
    关于Application.DoEvents()==转
    进程间通信方式【转】
    30岁后程序员的出路[转]
    git实用操作21条
    where T:new() 是什么意思
    使用Chrome console提取页面数据
    Maven入门2-pom.xml文件与settings.xml文件
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10141523.html
Copyright © 2011-2022 走看看