LeetCode Intersection of Two Arrays

Description

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

The original problem is here.

My Solution

I solve this problem in C++, as below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
map<int, int> freq;
vector<int> res;
for (int i = 0; i < nums1.size(); i++) {
freq[nums1[i]] = 1;
}
for (int i = 0; i < nums2.size(); i++) {
if(freq.find(nums2[i]) != freq.end()) {
freq[nums2[i]] = 2;
}
}

for(map<int,int>::iterator iter = freq.begin(); iter != freq.end(); iter++) {
if(iter->second == 2) {
res.push_back(iter->first);
}
}
return res;
}
};

Note

To solve the problem, traverse the two arrays, use hashmap to store the numbers and count the numbers which are both in the two arrays.