两个数组的交集
题目解析
题目要求求给定两个数组的交集,输出结果中元素都是唯一的。由于题目没有给定其他条件限制,所以我们需要考虑到数组长度很大的情况,在解题时可以使用long long类型来定义指针。
实现思路一:枚举
通过两层for循环,对所有元素进行比较,相同的放入结果数组中。同时,需要与结果数组中已有元素进行对比,若已经存在该元素,则不重复放入。
class Solution {
using ll = long long;
public:
bool isexisted(vector<int>& ret, int a){
for(auto i : ret){
if(a == i) return true;
}
return false;
}
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
ll m = nums1.size(), n = nums2.size();
vector<int> ret;
for(int i = 0; i < m; i++){
for (int j = 0; j < n; j++){
if(nums1[i] == nums2[j] && !isexisted(ret, nums1[i])){
ret.push_back(nums1[i]);
}
}
}
return ret;
}
};
实现思路二:双指针
先将两个数组分别进行排序,之后用两个指针从左至右依次比较。当两者相同时,判断是否已放入ret数组,若否,则放入。否则,指针继续右移。且当两个数组之一已全部做完比较,则无需再对另一数组的剩余元素进行比较了,大大降低了时间复杂度。
class Solution {
using ll = long long;
public:
bool isexisted(vector<int>& ret, int a){
for(auto i : ret){
if(a == i) return true;
}
return false;
}
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
vector<int> ret;
ll i = 0, j = 0;
while(i < nums1.size() && j < nums2.size()){
if(nums1[i] < nums2[j]) i++;
else if (nums1[i] > nums2[j]) j++;
else{
if(!isexisted(ret, nums1[i])) ret.push_back(nums1[i]);
i++;
j++;
}
}
return ret;
}
};