[leetcode] 349. 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.

这道题是找集合交集,题目难度为Easy。


最直观的想法是用Hash Table来存储一个集合中出现的数字,然后再依次比对另一个集合中的数字,相同的加入最终结果。由于集合可能有重复数字,所以在比对到一个相同数字之后将其在Hash Table中的标志置为“不存在”。具体代码:

class Solution {
public:
    vector intersection(vector& nums1, vector& nums2) {
        unordered_map hash;
        vector ret;
        
        for(auto num:nums1) hash[num] = 1;
        for(auto num:nums2) {
            if(hash[num]) {
                ret.push_back(num);
                hash[num] = 0;
            }
        }
        
        return ret;
    }
};

另外还可以排序之后依次比对,不过排序时间复杂度较高,这里就不推荐了。

你可能感兴趣的:(leetcode)