forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
intersection-of-multiple-arrays.cpp
76 lines (73 loc) · 2.22 KB
/
intersection-of-multiple-arrays.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Time: O(n * l + r), n = len(nums), l = len(nums[0])
// Space: O(r), r = max(nums)-min(nums)
// freq table, counting sort
class Solution {
public:
vector<int> intersection(vector<vector<int>>& nums) {
static const int MAX_NUM = 1000;
vector<int> cnt(MAX_NUM + 1);
for (const auto& num : nums) {
for (const auto& x : num) {
++cnt[x];
}
}
vector<int> result;
for (int i = 1; i <= MAX_NUM; ++i) {
if (cnt[i] == size(nums)) {
result.emplace_back(i);
}
}
return result;
}
};
// Time: O(n * l + r), n = len(nums), l = len(nums[0]), r = max(nums)-min(nums)
// Space: O(l)
// hash table, counting sort
class Solution2 {
public:
vector<int> intersection(vector<vector<int>>& nums) {
unordered_set<int> lookup(cbegin(nums[0]), cend(nums[0]));
for (int i = 1; i < size(nums); ++i) {
unordered_set<int> new_lookup;
for (const auto& x : nums[i]) {
if (lookup.count(x)) {
new_lookup.emplace(x);
}
}
lookup = move(new_lookup);
}
if (empty(lookup)) {
return {};
}
const int mn = *min_element(cbegin(lookup), cend(lookup));
const int mx = *max_element(cbegin(lookup), cend(lookup));
vector<int> result;
for (int i = mn; i <= mx; ++i) {
if (lookup.count(i)) {
result.emplace_back(i);
}
}
return result;
}
};
// Time: O(n * l + llogl), n = len(nums), l = len(nums[0])
// Space: O(l)
// hash table, sort
class Solution3 {
public:
vector<int> intersection(vector<vector<int>>& nums) {
unordered_set<int> lookup(cbegin(nums[0]), cend(nums[0]));
for (int i = 1; i < size(nums); ++i) {
unordered_set<int> new_lookup;
for (const auto& x : nums[i]) {
if (lookup.count(x)) {
new_lookup.emplace(x);
}
}
lookup = move(new_lookup);
}
vector<int> result(cbegin(lookup), cend(lookup));
sort(begin(result), end(result));
return result;
}
};