Leetcode :Intersection of Two Arrays 两个数组的交集

LeetCode349. Intersection of Two Arrays

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.

题目是求两个数组的交集,交集不能有重复元素,即求两个数组都存在的数字


思路:

题目要求交集没有重复元素,可以先对两个数组进行去重,考虑到要比较两个数组元素的大小,可以将两个数组填充到set容器中,set容器可以自动去重,自动排序,对于排序好的数组,设置两个指针分别从头遍历,若指针位置两个数字相同,则添加到结果数组,两个指针位置向后移动,若不相等,指向小的那个指针向后移动:


class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
	set<int> s1(nums1.begin(), nums1.end());
	set<int> s2(nums2.begin(), nums2.end());
	vector<int> res;
	set<int>::iterator it1 = s1.begin(), it2 = s2.begin();
	while (it1 != s1.end() && it2 != s2.end()){
		if (*it1 == *it2){
		res.push_back(*it1);
		it1++;
		it2++;
	}
		else if (*it2 > *it1) it1++;
		else it2++;
	}
	return res;
}
};


Leetcode 350 Intersection of Two Arrays II

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2, 2].

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

这题和上题的不同之处在于结果要求将交集的所有元素都添加到结果中,可以有重复元素,解法和上题相似,只要去掉去重的步骤即可,所以可以使用sort将两个数组排序,在进行交集查询:


class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        sort(nums1.begin(),nums1.end());
        sort(nums2.begin(),nums2.end());
        vector<int> res;
        vector<int>::iterator it1 = nums1.begin(),it2 = nums2.begin();
        while(it1!=nums1.end()&&it2!=nums2.end()){
            if(*it1 == *it2){
                res.push_back(*it1);
                it1++;
                it2++;
            }
            else if(*it1>*it2) it2++;
            else it1++;
        }
        return res;
    }
};
这种解法的空间复杂度O(n+m),大神的解法还没看,看后再更新。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值