forked from rui-yan/LeetCode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
intersection-of-two-arrays.cpp
79 lines (68 loc) · 2 KB
/
intersection-of-two-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
77
78
79
// Time: O(m + n)
// Space: O(min(m, n))
// Hash solution.
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
if (nums1.size() > nums2.size()) {
return intersection(nums2, nums1);
}
unordered_set<int> lookup{nums1.cbegin(), nums1.cend()};
vector<int> result;
for (const auto& i : nums2) {
if (lookup.count(i)) {
result.emplace_back(i);
lookup.erase(i);
}
}
return result;
}
};
// Time: O(max(m, n) * log(max(m, n)))
// Space: O(1)
// Binary search solution.
class Solution2 {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
if (nums1.size() > nums2.size()) {
return intersection(nums2, nums1);
}
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
vector<int> result;
auto it = nums2.cbegin();
for (const auto& i : nums1) {
it = lower_bound(it, nums2.cend(), i);
if (it != nums2.end() && *it == i) {
result.emplace_back(*it);
it = upper_bound(it, nums2.cend(), i);
}
}
return result;
}
};
// Time: O(max(m, n) * log(max(m, n)))
// Space: O(1)
// Two pointers solution.
class Solution3 {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
vector<int> result;
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
auto it1 = nums1.cbegin(), it2 = nums2.cbegin();
while (it1 != nums1.cend() && it2 != nums2.cend()) {
if (*it1 < *it2) {
++it1;
} else if (*it1 > *it2) {
++it2;
} else {
if (result.empty() || result.back() != *it1) {
result.emplace_back(*it1);
}
++it1, ++it2;
}
}
return result;
}
};