看答案罢了
https://leetcode-cn.com/problems/random-pick-with-weight/
(1)
0.0<=Math.random()<1.0
0.0<=totalMath.random()<total
1<=totalMath.random()+1<total+1
1<=total*Math.random()+1<=total
(2)这是什么样的二分查找
找到第一个大于等于pre[x]的下标
https://blog.csdn.net/weixin_42970433/article/details/118667111
class Solution {
int sum=0;
int len;
int[] pre;
public Solution(int[] w) {
//计算sum(w)
this.len=w.length;
for(int ww:w){
this.sum+=ww;
}
pre=new int[len];
//计算w[i]前缀和
pre[0]=w[0];
for(int i=1;i<len;i++){
pre[i]=pre[i-1]+w[i];
}
}
public int pickIndex() {
int x=(int)(sum*Math.random())+1;
return find(x);
}
public int find(int x){
int left=0,right=len-1;
int mid=(right-left)/2+left;
while(left<=right){
mid=(right-left)/2+left;
if(pre[mid]<x){
left=mid+1;
}
else{
right=mid-1;
}
}
return left;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(w);
* int param_1 = obj.pickIndex();
*/