带权重的随机选择算法
528. 按权重随机选择
不使用二分法:
class Solution {
private:
vector<int> preSum;
int N = 0;
public:
Solution(vector<int>& w) {
srand(time(0));
preSum.push_back(0);
for (int i = 1; i <= w.size(); i++) {
preSum.push_back(preSum[i-1] + w[i-1]);
}
N = preSum[w.size()];
}
int pickIndex() {
int randNum = (rand() % N) + 1;
for (int i = 1; i < preSum.size(); i++) {
if (randNum > preSum[i-1] && randNum <= preSum[i]) {
return i-1;
}
}
return -1;
}
};
使用二分法:
class Solution {
private:
vector<int> preSum;
int N = 0;
public:
Solution(vector<int>& w) {
preSum.push_back(0);
for (int i = 1; i <= w.size(); i++) {
preSum.push_back(preSum[i-1] + w[i-1]);
}
N = preSum[w.size()];
}
int pickIndex() {
// srand(time(0));
int randNum = (rand() % N) + 1;
cout << "randNum:" << randNum << endl;
int left = 0, right = preSum.size();
while (left < right) {
int mid = left + (right - left) / 2;
if (randNum > preSum[mid-1] && randNum <= preSum[mid]) {
return mid - 1;
}
else if (preSum[mid] < randNum) {
left = mid + 1;
}
else if (preSum[mid] > randNum) {
right = mid;
}
}
return left;
}
};
标签:int,Solution,randNum,算法,vector,随机,LBLD,preSum
From: https://www.cnblogs.com/yangxuanzhi/p/17322687.html