-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0350-Intersection_of_Two_Arrays_II.cpp
More file actions
103 lines (91 loc) · 2.21 KB
/
0350-Intersection_of_Two_Arrays_II.cpp
File metadata and controls
103 lines (91 loc) · 2.21 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*******************************************************************************
* 0350-Intersection_of_Two_Arrays_II.cpp
* Billy.Ljm
* 02 July 2024
*
* =======
* Problem
* =======
* https://leetcode.com/problems/intersection-of-two-arrays-ii/
*
* Given two integer arrays nums1 and nums2, return an array of their
* intersection. Each element in the result must appear as many times as it
* shows in both arrays and you may return the result in any order.
*
* ===========
* My Approach
* ===========
* We can make a set out of the smaller array, and iterate through the larger
* array to check if each element is in the set.
*
* This has a time complexity of O(n log(m)) and space complexity of O(m), where
* n and m are the length of the longer and shorter array respectively.
******************************************************************************/
#include <iostream>
#include <vector>
#include <set>
using namespace std;
/**
* << operator for vectors
*/
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
os << "[";
for (const auto elem : v) {
os << elem << ",";
}
if (v.size() > 0) os << "\b";
os << "]";
return os;
}
/**
* Solution
*/
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
vector<int> out;
multiset<int> sett;
vector<int> *shortarr, *longarr;
// find longer and shroter array
if (nums1.size() < nums2.size()) {
shortarr = &nums1;
longarr = &nums2;
}
else {
shortarr = &nums2;
longarr = &nums1;
}
// create set
for (int i : *shortarr) {
sett.insert(i);
}
// find intersect
for (int i : *longarr) {
auto itr = sett.find(i);
if (itr != sett.end()) {
out.push_back(i);
sett.erase(itr);
}
}
return out;
}
};
/**
* Test cases
*/
int main(void) {
Solution sol;
vector<int> nums1, nums2;
// test case 1
nums1 = { 1,2,2,1 };
nums2 = { 2,2 };
std::cout << "intersect(" << nums1 << ", " << nums2 << ") = ";
std::cout << sol.intersect(nums1, nums2) << std::endl;
// test case 2
nums1 = { 4,9,5 };
nums2 = { 9,4,9,8,4 };
std::cout << "intersect(" << nums1 << ", " << nums2 << ") = ";
std::cout << sol.intersect(nums1, nums2) << std::endl;
return 0;
}