528. Random Pick with Weight

Posted gopanama

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了528. Random Pick with Weight相关的知识,希望对你有一定的参考价值。

每个位置都是边界 二分法找

 

 

 1 class Solution {
 2     Random random = new Random(); //记得初始化
 3     int[] arr;
 4 
 5     public Solution(int[] w) {
 6         arr = new int[w.length];
 7         arr[0] = w[0];
 8         for(int i = 1; i < w.length; i++){
 9             arr[i] = arr[i-1] + w[i];
10         }
11         
12     }
13     
14     public int pickIndex() {
15         // System.out.println(arr[0]);
16         int num = random.nextInt(arr[arr.length - 1]) + 1;
17         int index = Arrays.binarySearch(arr, num);
18         if(index < 0){
19             index = -(index+1);
20         }
21         return index;
22         
23     }
24 }

 

以上是关于528. Random Pick with Weight的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode]528. Random Pick with Weight按权重挑选索引

leetcode 528. Random Pick with Weight

LeetCode 528. Random Pick with Weight / 497. Random Point in Non-overlapping Rectangles

leetcode 528 按权重随机选择

710. Random Pick with Blacklist

710. Random Pick with Blacklist - LeetCode