题目链接: https://leetcode.com/problems/intersection-of-two-arrays/
难度: 简单
归类 : 数组操作, 二分查找, set,unordered_set
给定两个数组,编写一个函数来计算它们的交集
示例:
示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2]
示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [9,4]
主要使用c++进行了解答,以及经典题解和尝试改进的最优/最简洁解法。
c++解法(set)
对两个数组分别进行for循环,分别放入两个set中,然后遍历求两个set共有的值。
#c++解法,假设len1=N.len2=M,则时间复杂度为O(max(M,N))
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
int len1 = nums1.size();
int len2 = nums2.size();
set<int> set1;
set<int> set2;
for(int i = 0; i < len1; i++){
set1.insert(nums1[i]);
}
for(int i = 0; i < len2; i++){
set2.insert(nums2[i]);
}
vector<int> res;
set<int>::iterator it = set1.begin();
for(;it!=set1.end();it++){
if(set2.find(*it) != set2.end()){
res.push_back(*it);
}
}
return res;
}
};
时间复杂度: O(N+M)
空间复杂度: O(N+M)
提交结果:
Runtime: 8 ms, faster than 88.53% of C++ online submissions for Intersection of Two Arrays.
Memory Usage: 10.9 MB, less than 6.67% of C++ online submissions for Intersection of Two Arrays.
c++解法(set法的改进 : unordered_set)
unordered_set比set的优点在于,它是基于哈希表,能够以常数级别的时间存储和取出数据,但其内存占用较大。
#unordered_set
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> set1(nums1.begin(), nums1.end());
vector<int> res;
for(auto a : nums2){
if(set1.count(a)){
res.push_back(a);
set1.erase(a);
}
}
return res;
}
};
时间复杂度: O(N)
空间复杂度: 未知
提交结果:
Runtime: 8 ms, faster than 88.53% of C++ online submissions for Intersection of Two Arrays.
Memory Usage: 10.8 MB, less than 6.67% of C++ online submissions for Intersection of Two Arrays.
c++解法(普通单set)
使用普通的单个set来完成,空间复杂度较低。根据结果可见,空间就降一点,时间涨很多。
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
set<int> s(nums1.begin(), nums1.end());
vector<int> out;
for (int x : nums2)
if (s.erase(x))
out.push_back(x);
return out;
}
时间复杂度: 未知
空间复杂度: 未知
提交结果:
Runtime: 12 ms, faster than 47.42% of C++ online submissions for Intersection of Two Arrays.
Memory Usage: 10.4 MB, less than 6.67% of C++ online submissions for Intersection of Two Arrays.
在unordered_set解法的基础上,找到了一个可以将count和erase结合的方法。即在判断unordered_set中是否存在某元素时,可以使用set1.erase(a)来判断,同时可以删去该元素。
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> set1(nums1.begin(), nums1.end());
vector<int> res;
for(auto a : nums2){
if(set1.erase(a)){
res.push_back(a);
}
}
return res;
}
};
时间复杂度: 未知
空间复杂度: 未知
提交结果:
Runtime: 12 ms, faster than 47.42% of C++ online submissions for Intersection of Two Arrays.
Memory Usage: 10.8 MB, less than 6.67% of C++ online submissions for Intersection of Two Arrays.
可见,并不怎么减时间,按理来说应该减时间的,看运气吧…