<LeetCode OJ> 349 / 350 Intersection of Two Arrays(I / II)

Total Accepted: 3212  Total Submissions: 6814  Difficulty: Easy

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.

分析:DONE

求两个数组的交集(其结果是一系列数字)。只要数组2中的数字出现在数组1中,他就是交集。

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        vector<int> result;
        unordered_map<int,int> mapping;
        for(int i=0;i < nums1.size();i++)
            mapping.insert(make_pair(nums1[i],i+1));
        for(int i=0;i < nums2.size();i++)
        {
            if(mapping[nums2[i]]>0)//找到了交集的数字,获取结果
            {
                mapping[nums2[i]]=0;//清零,该数不再允许被查找到
                result.push_back(nums2[i]);
            }
        }
        return result;   
    }
};




Total Accepted: 3237  Total Submissions: 7617  Difficulty: Easy

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.

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to num2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

分析:DONE

先让数组有序,再双指针遍历即可,有相同元素就获取结果,然后判断下一对

空间复杂度为O(N*lg(N)),时间复杂度为O(1)

N是两个数组的较长者。

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        vector<int> result;
        sort(nums1.begin(),nums1.end());
        sort(nums2.begin(),nums2.end());//排序了才能有序的移动
        int i=0;
        int j=0;
        while(i < nums1.size() && j < nums2.size())//双指针遍历
        {
            if(nums1[i] < nums2[j])//移动较小者
                i++;
            else if(nums1[i] > nums2[j])
                j++;
            else//相等,获取结果
             {
                result.push_back(nums1[i]);
                i++;j++;
             }
        }
        return result;  
    }
};


注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/51458500

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值