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.

 1 class Solution {
 2     Random random;
 3     int[] wSums;
 4 
 5     public Solution(int[] w) {
 6         this.random = new Random();
 7         for (int i = 1; i < w.length; ++i) {
 8             w[i] += w[i - 1];
 9         }
10         this.wSums = w;
11     }
12 
13     public int pickIndex() {
14         int len = wSums.length;
// if w is 2,3, then there are 5 slots. If we randomly select a value between 1 and 5. If the value is less than or equal to 2, then, it belong to the first item, otherwise, it belongs to the second item.
15 int idx = random.nextInt(wSums[len - 1]) + 1; 16 int left = 0, right = len - 1; 17 // in essence, we need to find out the min value which is greater than or equal to the target. 18 while (left <= right) { 19 int mid = left + (right - left) / 2; 20 if (wSums[mid] == idx) { 21 return mid; 22 } else if (wSums[mid] < idx) { 23 left = mid + 1; 24 } else { 25 right = mid - 1; 26 } 27 } 28 return left; 29 } 30 }

 

posted @ 2019-07-15 09:19  北叶青藤  阅读(106)  评论(0编辑  收藏  举报