-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathRandom Pick with Blacklist.cpp
50 lines (46 loc) · 1.29 KB
/
Random Pick with Blacklist.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
38
39
40
41
42
43
44
45
46
47
48
49
50
// Solution 1: Binary Search. O(log)
class Solution {
vector<int> v;
std::random_device rd;
int mod;
public:
Solution(int N, vector<int> blacklist) {
mod = N - blacklist.size();
sort(blacklist.begin(), blacklist.end());
v = blacklist;
v.push_back(N);
for (int i = 0; i < v.size(); i++) v[i] -= i;
}
int pick() {
int index = rd() % mod;
auto it = upper_bound(v.begin(), v.end(), index);
return index + (it - v.begin());
}
};
// Solution 2: hash_map; O(1)
class Solution {
random_device rd;
unordered_map<int, int> updated_index;
int mod;
public:
Solution(int N, vector<int>& blacklist) {
mod = N - blacklist.size();
set<int> blacklist_set(blacklist.begin(), blacklist.end());
int swap_num = N - 1;
for (int blacklist_element : blacklist_set) {
if (blacklist_element >= mod) break;
while (blacklist_set.count(swap_num) > 0) {
swap_num--;
}
updated_index[blacklist_element] = swap_num;
swap_num--;
}
}
int pick() {
int index = rd() % mod;
if (updated_index.count(index) > 0) {
return updated_index[index];
}
return index;
}
};