题解:
class Solution {
public:
vector<int> w2;
//总和
int range;
Solution(vector<int>& w):range(0) {
for(int i = 0;i<w.size();i++){
range+=w[i];
w2.push_back(range);
}
}
int pickIndex() {
//随机地获取下标 选取下标的概率与w[i]成正比
//rd位于0-(range-1)
int rd = rand()%range;
int l = 0;
int r = w2.size()-1;
//二分法获取下标 所得下标l是第一个比目标值大的元素
while(l<r){
int mid = l + r >> 1;
if(w2[mid]>rd){
r = mid;
}else{
l = mid+1;
}
}
return l;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(w);
* int param_1 = obj->pickIndex();
*/
举例:[1,2,3]
总和6 w2[1,3,6],rd随机在0-5之间
则rd为0返回下标0 概率为1/6
rd为1返回下标1
rd为2返回下标1 概率为1/3
rd为3返回下标2
rd为4返回下标2
rd为5返回下标2 概率为1/2