forked from kaidul/LeetCode_problems_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRandom_Pick_Index.cpp
37 lines (35 loc) · 1.03 KB
/
Random_Pick_Index.cpp
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
// Reservoir sampling: http://www.geeksforgeeks.org/reservoir-sampling/
class Solution {
vector<int> arr;
// default_random_engine generator;
public:
Solution(vector<int> nums) {
srand(time(NULL));
arr = nums;
// generator = default_random_engine();
}
int pick(int target) {
int result = -1, cnt = 0;
for(int i = 0; i < arr.size(); ++i) {
if(arr[i] != target) {
continue;
}
if(cnt == 0) { result = i; cnt++; }
else { cnt++; if(rand() % cnt == 0) result = i; }
// AC but TLE :(
/*
uniform_int_distribution<int> distribution(0, cnt); // will geenrate random number between [0, cnt]
if(distribution(generator) == cnt) {
result = i;
}
++cnt;
*/
}
return result;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/