LeetCode 528. 按权重随机选择
思路
预处理前缀和,将数组映射到数轴上,产生数组长度的随机数,判断落点位置,二分查找属于哪一个区间
class Solution {
public:
vector<int> s;
Solution(vector<int>& w) {
s = w;
for (int i = 1; i < w.size(); i ++ ) {
s[i] += s[i - 1];
}
}
int pickIndex() {
int x = rand() % s.back() + 1;
return lower_bound(s.begin(), s.end(), x) - s.begin();
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(w);
* int param_1 = obj->pickIndex();
*/