leetcode 349.两个数组的交集
大家好,我是小学五年级在读的蒟蒻,专注于后端,一起见证蒟蒻的成长,您的评论与赞与关注是我的最大动力,如有错误还请不吝赐教,万分感谢。一起支持原创吧!纯手打有笔误还望谅解。
题目描述
给定两个数组,编写一个函数来计算它们的交集。
题解一
思路:使用循环遍历两个数组,如果遇到相同的元素则存放到result容器中,最后返回result
代码部分后期补
题解二
思路:由于只需要遍历数组所以使用unordered容器不必排序提高效率,使用set容器将一个数组的元素存放进去,然后遍历set容器将每个元素与第二个数组的元素相匹配,如果相同则将元素加入result容器中,最后将result容器的元素存放到vector容器中返回
/*
* @lc app=leetcode.cn id=349 lang=cpp
*
* [349] 两个数组的交集
*/
// @lc code=start
class Solution
{
public:
vector<int> intersection(vector<int> &nums1, vector<int> &nums2)
{
unordered_set<int> result_set;
unordered_set<int> nums_set(nums1.begin(), nums1.end());
for (int num : nums2)
{
if (nums_set.find(num) != nums_set.end())
{
result_set.insert(num);
}
}
return vector<int>(result_set.begin(), result_set.end());
}
};
// @lc code=end