最终的结果是left的索引 代表大于等于target的最小索引,
用左边界的二分搜索原因是,如果没有目标值,left大于或者等于target
class Solution {private int[] preSum;private Random rand=new Random();public Solution(int[] w) {//写前缀和数组preSum=new int[w.length+1];for(int i=1;i<=w.length;i++){preSum[i]=preSum[i-1]+w[i-1];}}public int pickIndex() {int l = preSum.length;int target = rand.nextInt(preSum[l - 1]) + 1;return findLeft(preSum,target)-1;// 别忘了前缀和数组 preSum 和原始数组 w 有一位索引偏移}public int findLeft(int[] nums,int target){int left=0,right=nums.length-1;while(left<=right){int mid=(left+right)/2;if(target>nums[mid]){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();*/