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) {
vector<int> nums = {};
int mark = 0;
map<int, int> maps;
int count1 = nums1.size();
int count2 = nums2.size();
if (nums2.size() < nums1.size())
{
count1 = nums2.size();
count2 = nums1.size();
mark = 1;
}
for (int i = 0; i < count1; i++)
{
for (int j = 0; j < count2; j++)
{
if (mark == 1)
{
if (nums2[i] == nums1[j])
{
maps[nums1[j]]++;
}
}
if (mark == 0)
{
if (nums1[i] == nums2[j])
{
maps[nums1[i]]++;
}
}
}
}
for (map<int, int>::iterator iter = maps.begin(); iter != maps.end(); iter++)
{
nums.push_back(iter->first);
}
return nums;
}
};
其他人解法:
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> m(nums1.begin(), nums1.end());
vector<int> res;
for (auto a : nums2)
if (m.count(a)) {
res.push_back(a);
m.erase(a);
}
return res;
}
};
这是set,无序表里面是不含有相同元素的,而且查询速度比map块,里面的组织是无序的。