Comment on page
349.Intersection of Two Arrays
349.Intersection of Two Arrays
难度:Easy
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2]
示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [9,4]
说明:
输出结果中的每个元素一定是唯一的。
我们可以不考虑输出结果的顺序。
代码如下:
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int>n1(nums1.begin(),nums1.end());
unordered_set<int>n2(nums2.begin(),nums2.end());
vector<int> res;
for(auto each: n1)
{
// cout<< each<<endl;
if(n2.count(each)) res.push_back(each);
}
return res;
}
};
执行用时 :20 ms, 在所有 C++ 提交中击败了31.29%的用户 内存消耗 :9.4 MB, 在所有 C++ 提交中击败了39.10%的用户
Last modified 1yr ago