-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0398.cpp
More file actions
36 lines (30 loc) · 818 Bytes
/
Copy path0398.cpp
File metadata and controls
36 lines (30 loc) · 818 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
#pragma GCC optimize("fast")
static auto _ = []() {
ios_base::sync_with_stdio(false);
cin.tie(NULL), cout.tie(NULL);
return 0;
}();
// O(n) pick, O(1) space
class Solution {
const vector<int> &nums;
public:
Solution(const vector<int> &nums) : nums(nums) {}
int pick(int target) {
int n = 0, ans = -1;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != target) continue;
if (rand() % ++n == 0) ans = i;
}
return ans;
}
};
// O(1) pick, O(n) space
class Solution {
unordered_map<int, vector<int>> um;
public:
Solution(const vector<int> &nums) {
for (int i = 0; i < nums.size(); i++)
um[nums[i]].push_back(i);
}
int pick(int target) { return um[target][rand() % um[target].size()]; }
};