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> ans;
//if((nums1.empty()) || (nums2.empty()))
// return nums;
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
int i = 0, j = 0;
while((i < nums1.size()) && (j < nums2.size()))
{
if(nums1[i] == nums2[j])
{
if(ans.empty()||nums1[i] != ans[ans.size()-1]) // 如果这里把ans.empty 放到||后面就会报错。 要先检测是否是空!
ans.push_back(nums1[i]);
++i;
++j;
}
else nums1[i]<nums2[j]? i++:j++;
}
return ans;
}
};看不懂的答案。。
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;
}
};
本文介绍了一种计算两个整数数组交集的算法实现。通过排序和哈希表两种方法来找出两个数组中的共有元素,并确保结果中每个元素都是唯一的。提供了详细的C++代码示例。
1352

被折叠的 条评论
为什么被折叠?



