LeetCode 350. Intersection of Two Arrays II

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

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]

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 nums2‘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?

解析:

两个数组,求两个数组的交集,要注意的是如果同一个元素在两个数组中均出现多次,则都要返回。

解法1:

首先对两个数组进行排序,对数组1中的每个元素,判断是否在数组2中出现。这里需要注意的是要记录上一次出现的位置,作为本次在数组2中的查找的起始位置。

代码如下:

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        vector<int> result;
        if(nums1.size() == 0 || nums2.size()== 0)
            return result;
        vector<int> :: iterator it = nums2.begin();
        sort(nums1.begin(), nums1.end());
        sort(nums2.begin(), nums2.end());
        for(auto &num: nums1)
        {
            vector<int>::iterator temp = find(it, nums2.end(), num);
            if(temp != nums2.end())
            {
                result.push_back(num);
                it = temp+1;
            }
        }
        return result;
    }
};

解法2:

采用HashTable的方式,将数组1中的元素存放在一个map中,key是元素,value是出现次数。对于数组2中的每个元素,判断是否在map中出现,若出现则把map中对应元素的value减一。具体代码如下:

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        unordered_map<int, int> dict;
        vector<int> result;
        if(nums1.size() == 0 || nums2.size() == 0)
            return result;
        for(auto &num : nums1)
            dict[num] ++;
        for(auto &num : nums2)
        {
            if(dict.find(num) != dict.end() && --dict[num] >= 0)
                result.push_back(num);
        }
        return result;
    }
};

运行结果如下:

Add a Comment

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据