首页 > 其他 > 详细

528. Random Pick with Weight

时间:2018-10-28 10:52:10      阅读:168      评论:0      收藏:0      [点我收藏+]

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

 

 

 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

原文:https://www.cnblogs.com/goPanama/p/9864118.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!