# 349. Intersection of Two Arrays

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.

class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> hs1;
unordered_set<int> hs2;
vector<int> vi;
int len1=nums1.size();
int len2=nums2.size();
for(int i=0;i<len1;i++)
hs1.insert(nums1[i]);
for(int i=0;i<len2;i++)
hs2.insert(nums2[i]);

for(auto it1=hs1.begin();it1!=hs1.end();it1++)
for(auto it2=hs2.begin();it2!=hs2.end();it2++)
if(*it1==*it2)
vi.push_back(*it1);

return vi;

}
};

Runtime: 32 ms

class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> set1;
int len2=nums2.size();
for(int i=0;i<len2;i++)
if(find(nums1.begin(),nums1.end(),nums2[i])!=nums1.end())
set1.insert(nums2[i]);
return vector<int> (set1.begin(),set1.end());

}
};

Runtime: 8 ms

class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
vector<int> vi;
unordered_set<int> m(nums1.begin(),nums1.end());
for(auto a:nums2)
if(m.count(a))
{
vi.push_back(a);
m.erase(a);
}
return vi;
}
};


class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
std::sort(nums1.begin(),nums1.end());
std::sort(nums2.begin(),nums2.end());
vector<int> res;
int len1=nums1.size();
int len2=nums2.size();
int i=0,j=0;
while(i<len1&&j<len2)
{
if(nums1[i]<nums2[j])
i++;
else if(nums1[i]>nums2[j])
j++;
else
{
if(res.empty()||res.back()!=nums1[i])
res.push_back(nums1[i]);
i++;
j++;
}
}
return res;
}
};

05-28 1934

05-27 2234

10-11 184

05-18 5493

05-18 1995

05-19 724

05-25 1639

05-28 2651

06-26 1678

08-27 704