代码:
看不懂题 看了题解才懂题是什么意思..
二分查找完结撒花!🎉
class Solution {int[] pre;int total;public Solution(int[] w) {int n = w.length;total = Arrays.stream(w).sum();pre = new int[n];pre[0] = w[0];for(int i=1;i<n;i++){pre[i] = pre[i-1] + w[i];}}public int pickIndex() {int x = (int)(Math.random()*total) +1;return binarySearch(x);}public int binarySearch(int x){int l=0,r=pre.length-1;while(l<r){int m = l + (r-l)/2;if(pre[m]<x){l = m+1;}else{r = m;}}return l;}}