【代码随想录】LC 349. 两个数组的交集

前言

本专栏文章为《代码随想录》书籍的刷题题解以及读书笔记,如有侵权,立即删除。

一、题目

1、原题链接

349. 两个数组的交集

2、题目描述

在这里插入图片描述

二、解题报告

1、思路分析

(1)由于题目中要求输出结果中的每个元素是唯一的。所以需要对结果进行去重,而又需要快速判断是否是两数组的交集。我们可以使用 unordered_set,其底层是哈希表,存/取时间为O(1),既满足了存取效率,同时也满足了去重的要求。
(2)我们可以首先将数组1中的元素去重放到哈希表中,然后依次来遍历数组2中的元素,如果其在哈希表中存在,则为两数组的交集;否则,则不是。

2、时间复杂度

时间复杂度O(n)

3、代码详解

class Solution {
   
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
   
        unordered_set<int> res;    //存放结果
        unordered_set<int> temp(nums1.begin(), nums1.end());  //将nums1中元素去重存放到temp中
        //遍历nums2
        for (int num : nums2) {
   
            //如果nums2中元素在temp中存在,说明该元素是数组的交集
            if (temp.find(num) != temp.end()) {
   
                res.insert(num);
            }
        }
        return vector<int>(res.begin(), res.end());   //将结果类型强转为题目要求类型,返回结果
    }
};

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-02 02:16:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-02 02:16:02       101 阅读
  3. 在Django里面运行非项目文件

    2024-02-02 02:16:02       82 阅读
  4. Python语言-面向对象

    2024-02-02 02:16:02       91 阅读

热门阅读

  1. vue中使用stomp.js

    2024-02-02 02:16:02       62 阅读
  2. React详解

    2024-02-02 02:16:02       40 阅读
  3. @Async导致获取Bean异常‘com.sun.proxy.$Proxy124‘

    2024-02-02 02:16:02       45 阅读
  4. C语言实战三:图书管理系统

    2024-02-02 02:16:02       55 阅读
  5. Redis RCountDownLatch& RSemaphore的应用

    2024-02-02 02:16:02       59 阅读
  6. C++模板判断类中是否存在某个名称的成员函数

    2024-02-02 02:16:02       60 阅读
  7. ZooKeeper客户端实战

    2024-02-02 02:16:02       44 阅读
  8. 433. 最小基因变化

    2024-02-02 02:16:02       56 阅读
  9. MongoDB实战 – 用MongoDB Shell访问MongoDB数据库

    2024-02-02 02:16:02       53 阅读