528. 按权重随机选择
题目类型
题意
分析
前缀和 + 二分
时间复杂度
O ( ) O( ) O()
代码
class Solution {
int[] pre;
int sum;
public Solution(int[] w) {
pre = new int[w.length];
pre[0] = w[0];
for (int i = 1, len = w.length; i < len; i++) {
pre[i] = pre[i - 1] + w[i];
}
sum = Arrays.stream(w).sum();
}
public int pickIndex() {
int x = (int) (Math.random() * sum) + 1;
return binarySearch(x);
}
public int binarySearch(int x) {
int left = 0, right = pre.length - 1;
while (left < right) {
int mid = left + right >> 1;
if (pre[mid] >= x) right = mid;
else left = mid + 1;
}
return right;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(w);
* int param_1 = obj.pickIndex();
*/