题目链接
思路:前缀和+二分查找
- 首先我们新建一个前缀和数组,比如nums为[1,2,3,4],前缀和数组便为[1,3,6,10]
- 可以知道,nums数组的和就是前缀和数组的最后一个数(lastVal)
- 然后我们以lastVal为上界生成一个随机整数,也就是说整数的范围是[0,lastVal - 1]
- 对于生成的某个整数n,我们去寻找前缀和数组中比n大的最小的数
class Solution {
int[] sums;
Random random;
public Solution(int[] w) {
random = new Random();
sums = new int[w.length];
sums[0] = w[0];
for (int i = 1; i < w.length; i++) {
sums[i] += sums[i - 1] + w[i];
}
}
public int pickIndex() {
int target = random.nextInt(sums[sums.length - 1]);
int left = 0, right = sums.length - 1,result = 0;
while (left <= right) {
int mid = left + ((right - left) >> 1);
if (sums[mid] <= target)
left = mid + 1;
else {
result = mid;
right = mid - 1;
}
}
return result;
}
}