题目分析:C++使用unordered set装入其中一个数组,然后和另一数组比较,得到相同的元素;python可以用&或者自带的函数,有用字典的方式,回头再做
C++:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> s(nums1.begin() , nums1.end());
vector<int> v ;
for (auto x : nums2){
if (s.erase(x))
v.push_back(x);
}
return v;
}
Python:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1) & set(nums2))
# return set(nums1).intersection(set(nums2))
本文介绍了一种用于寻找两个整数数组交集的算法,分别用C++和Python实现。C++版本通过unordered_set进行高效查找,而Python则利用集合运算符&简化操作。两种方法均能有效找出两数组的共有元素。
706

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



