题目链接
题意
w
数组为权重数组,我们随机选择下标i
,按权重比 w[i]/total
,total
为w
数组权重之和。
解题思路
我们可以预处理出一个 w
数组的前缀和数组 pre
,然后随机从 [0,total)
中随机选择一个数,然后二分找到前缀和中,最小的大于选择的这个数的下标,这样随机选择就是按权重选择的。预处理前缀和数组时间复杂度O(n)
,二分查找时间复杂度 O(logn)
。
具体代码
class Solution {
public:
vector<int> pre;
Solution(vector<int>& w) {
pre.clear();
pre.push_back(w[0]);
for(int i=1; i<w.size(); ++i)
pre.push_back(pre[i-1]+w[i]);
}
int pickIndex() {
return upper_bound(pre.begin(),pre.end(),rand()%pre[pre.size()-1])-pre.begin();
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(w);
* int param_1 = obj->pickIndex();
*/