每日一题 LeetCode 528

看答案罢了

https://leetcode-cn.com/problems/random-pick-with-weight/
(1)
0.0<=Math.random()<1.0
0.0<=totalMath.random()<total
1<=total
Math.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();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值