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 intersection(vector& nums1, vector& nums2) {
        vector result;
        unordered_map 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 intersect(vector& nums1, vector& nums2) {
        vector 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

你可能感兴趣的:(LeetCode,OJ,LeetCode解题报告)