0%

June Leetcoding Challenge(6.5)

Random Pick with Weight

Solution

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:

1
2
3
4
Input: 
["Solution","pickIndex"]
[[[1]],[]]
Output: [null,0]

Example 2:

1
2
3
4
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 w. pickIndex has no arguments. Arguments are always wrapped with a list, even if there aren’t any.

思路:

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
int[] tmp;
Random rand;
public Solution(int[] w) {
this.tmp = w.clone();
this.rand = new Random();
for(int i=1;i<w.length;i++)
tmp[i] +=tmp[i-1];
}

public int pickIndex() {
int x = rand.nextInt(tmp[tmp.length-1])+1;
int index = Arrays.binarySearch(tmp,x);
if(index<0)
index = -(index+1);
return index;
}
}

/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(w);
* int param_1 = obj.pickIndex();
*/
-------------本文结束感谢您的阅读-------------

本文标题:June Leetcoding Challenge(6.5)

文章作者:Jungle

发布时间:2020年06月05日 - 08:34

最后更新:2020年06月05日 - 08:41

原始链接:http://yoursite.com/2020/06/05/LeetCodeJune5th/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Welcome to my other publishing channels