-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathintersection-of-two-arrays.cpp
74 lines (65 loc) · 1.14 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
// https://leetcode.com/problems/intersection-of-two-arrays/
class Solution
{
public:
vector<int> intersection(vector<int> &nums1, vector<int> &nums2)
{
int nums1Length = nums1.size();
int nums2Length = nums2.size();
vector<int> result;
// store the smaller sized vector in map to handle limited disk memory
if (nums1Length > nums2Length)
{
map<int, int> m;
map<int, int>::iterator itr;
for (int num : nums2)
{
itr = m.find(num);
if (itr != m.end())
{
itr->second++;
}
else
{
m.insert({num, 1});
}
}
for (int num : nums1)
{
itr = m.find(num);
if ((itr != m.end()) && (itr->second > 0))
{
result.push_back(num);
itr->second = 0;
}
}
}
else
{
map<int, int> m;
map<int, int>::iterator itr;
for (int num : nums1)
{
itr = m.find(num);
if (itr != m.end())
{
itr->second++;
}
else
{
m.insert({num, 1});
}
}
for (int num : nums2)
{
itr = m.find(num);
if ((itr != m.end()) && (itr->second > 0))
{
result.push_back(num);
itr->second = 0;
}
}
}
return result;
}
};