Example:
Therefore,
We map
Therefore, we should find a value in
class Solution {
public:
Solution(vector<int> &w) {
prefixSum.resize(w.size());
prefixSum[0] = w[0];
for (int i = 1; i < prefixSum.size(); ++i) {
prefixSum[i] = prefixSum[i - 1] + w[i];
}
}
int pickIndex() {
int x = rand() % prefixSum.back();
// Use binary search to find a prefix sum (prefixSum[middle])
// that is greater than x.
int left = 0, right = prefixSum.size() - 1;
while (left < right) {
int middle = left + (right - left) / 2;
if (prefixSum[middle] <= x) {
left = middle + 1;
} else {
right = middle;
}
}
if (prefixSum[left] <= x) {
++left;
}
return left;
}
private:
vector<int> prefixSum;
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(w);
* int param_1 = obj->pickIndex();
*/
Sloution
pickIndex
w
.Sloution
pickIndex
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up