-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0350_intersect.cc
73 lines (68 loc) · 1.22 KB
/
Problem_0350_intersect.cc
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
#include <algorithm>
#include <iostream>
#include <unordered_map>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Solution
{
public:
vector<int> intersect(vector<int> &nums1, vector<int> &nums2)
{
unordered_map<int, int> map1;
for (int num : nums1)
{
if (!map1.count(num))
{
map1.emplace(num, 1);
}
else
{
map1[num]++;
}
}
unordered_map<int, int> map2;
for (int num : nums2)
{
if (!map2.count(num))
{
map2.emplace(num, 1);
}
else
{
map2[num]++;
}
}
vector<int> ans;
for (auto &[key, _] : map1)
{
if (map2.count(key))
{
int n = std::min(map1.at(key), map2.at(key));
for (int i = 0; i < n; i++)
{
ans.push_back(key);
}
}
}
return ans;
}
};
void testIntersect()
{
Solution s;
vector<int> n1 = {1, 2, 2, 1};
vector<int> n2 = {2, 2};
vector<int> n3 = {4, 9, 5};
vector<int> n4 = {9, 4, 9, 8, 4};
vector<int> o1 = {2, 2};
vector<int> o2 = {9, 4};
EXPECT_TRUE(o1 == s.intersect(n1, n2));
EXPECT_TRUE(o2 == s.intersect(n3, n4));
EXPECT_SUMMARY;
}
int main()
{
testIntersect();
return 0;
}