Featured image of post Intersection of Two Arrays

Intersection of Two Arrays

349. 两个数组的交集

分析

  1. nums1 中的元素插入到哈希集合中
  2. 遍历 nums2,对于每一个元素,如果该元素在哈希集合中存在,就表示它是 nums1nums2 的交集中的元素
  3. 每次发现交集元素时,将其添加到结果数组 res 中,并从哈希集合中删除该元素,以保证结果中不包含重复元素

时间复杂度

时间复杂度 O(n + m)

空间复杂度

空间复杂度为 O(n)

C++代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution
{
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2)
    {
        std::unordered_set<int> hash;  // 用于存储 nums1 中的元素
        std::vector<int> res;           // 用于存储交集的结果

        // 将 nums1 中的所有元素插入到哈希集合中
        for (int x : nums1)
            hash.insert(x);

        // 遍历 nums2,如果元素存在于哈希集合中,则表示是交集的一部分
        for (int x : nums2)
            if (hash.count(x))  // 查找 x 是否在哈希集合中
            {
                res.push_back(x);  // 将交集元素添加到结果中
                hash.erase(x);     // 删除该元素,避免重复添加
            }

        return res;  // 返回交集结果
    }
};
Built with Hugo
Theme Stack designed by Jimmy