-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrandom_pick_index.cpp
More file actions
45 lines (41 loc) · 954 Bytes
/
random_pick_index.cpp
File metadata and controls
45 lines (41 loc) · 954 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
36
37
38
39
40
41
42
43
44
45
/*
* =====================================================================================
*
* Filename: random_pick_index.cpp
*
* Description: 528. Random Pick with Weight
*
* Version: 1.0
* Created: 11/06/2025 18:34:23
* Revision: none
* Compiler: gcc
*
* Author: xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <cstdlib>
#include <map>
#include <vector>
class Solution {
public:
Solution(std::vector<int>& w) {
for (int i = 0; i < w.size(); i++) {
sum_ += w[i];
indexes_[sum_] = i;
}
std::srand(std::time(0));
}
int pickIndex() {
int r = std::rand() % sum_;
auto it = indexes_.upper_bound(r);
if (it != indexes_.end()) {
return it->second;
}
return (--it)->second;
}
private:
std::map<int, int> indexes_;
int sum_ = 0;
};