-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path528.cpp
More file actions
35 lines (32 loc) · 819 Bytes
/
528.cpp
File metadata and controls
35 lines (32 loc) · 819 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public:
vector<int> prefixSum;
int sum = 0;
Solution(vector<int>& w) {
prefixSum.push_back(0);
for (auto& num : w) {
sum += num;
prefixSum.push_back(sum);
}
}
int binarySearch(int query) {
int left = 0;
int right = prefixSum.size();
while (left < right) {
int mid = left + (right - left) / 2;
if (prefixSum[mid] > query) right = mid;
else left = mid + 1;
}
return left;
}
int pickIndex() {
int rnd = rand() % sum;
int index = binarySearch(rnd) - 1;
return index;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(w);
* int param_1 = obj->pickIndex();
*/