Skip to content

Commit 22d0b59

Browse files
authored
Random
1 parent e1d1774 commit 22d0b59

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

Random pick with weight

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
public:
3+
vector<int> v;
4+
Solution(vector<int>& w)
5+
{
6+
v.push_back(w[0]);
7+
for(int i=1;i<w.size();i++){
8+
v.push_back(v[i-1]+w[i]);
9+
}
10+
}
11+
12+
int pickIndex() {
13+
int n= rand()%v[v.size()-1];
14+
auto it=upper_bound(v.begin(),v.end(),n);
15+
return it-v.begin();
16+
}
17+
};
18+
19+
/**
20+
* Your Solution object will be instantiated and called as such:
21+
* Solution* obj = new Solution(w);
22+
* int param_1 = obj->pickIndex();
23+
*/

0 commit comments

Comments
 (0)