Leetcode 528. Random Pick with Weight
Given an array w of positive integers where w[i] describes the weight of index i, write a function pickIndex that randomly picks an index in proportion to its weight.
Implement the Solution class:
class Solution {
public:
Solution(vector<int>& w);
int pickIndex();
};
Solution(vector<int>& w) Initializes the object with the given array w.int pickIndex() Returns a random index based on the weight distribution.w can take?w?#include <vector>
#include <cstdlib>
class Solution {
public:
Solution(std::vector<int>& w) : prefixSums(w.size(), 0) {
// Calculate the prefix sums
prefixSums[0] = w[0];
for (int i = 1; i < w.size(); ++i) {
prefixSums[i] = prefixSums[i - 1] + w[i];
}
}
int pickIndex() {
int totalSum = prefixSums.back();
int randWeight = rand() % totalSum;
// Binary search for the correct index
int low = 0, high = prefixSums.size() - 1;
while (low < high) {
int mid = low + (high - low) / 2;
if (randWeight >= prefixSums[mid]) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
private:
std::vector<int> prefixSums;
};
Solution constructor):
prefixSums[i] will hold the sum of w[0] to w[i].pickIndex method):
w.This solution ensures that the pickIndex operation is efficient even for large input sizes, striking a balance between preprocessing time and query time.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?