Binary Search:349. Intersection of Two Arrays
程序员文章站
2022-07-15 10:50:19
...
求两个数组相交的数字的集合,结果中不能有重复的。
想到了用set
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
int m = nums1.size(), n = nums2.size();
set<int> res;
vector<int> result;
for(int i = 0; i < m; ++i)
{
for(int j = 0; j < n; ++j)
{
if(nums1[i] == nums2[j])
{
res.insert(nums1[i]);
break;
}
}
}
for(auto a : res)
{
result.push_back(a);
}
return result;
}
};
看了大神代码,更简洁:
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
set<int> s(nums1.begin(), nums1.end()), res;
for (auto a : nums2) {
if (s.count(a)) res.insert(a);
}
return vector<int>(res.begin(), res.end());
}
};
推荐阅读
-
LeetCode C++ 454. 4Sum II【Hash Table/Sort/Two Pointers/Binary Search】
-
[LC] 349. Intersection of Two Arrays
-
349. Intersection of Two Arrays
-
LeetCode刷题笔记(Intersection of Two Arrays II)
-
LeetCode 350. Intersection of Two Arrays II
-
leetcode 349. Intersection of Two Arrays(C语言)10
-
LeetCode 350. Intersection of Two Arrays II
-
Binary Search:349. Intersection of Two Arrays
-
LeetCode 349. Intersection of Two Arrays
-
LeetCode-349. Intersection of Two Arrays