力扣 349.两个数组的交集

给定两个数组 nums1nums2 ,返回它们的交集 。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序

示例 1:

复制代码
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]

示例 2:

复制代码
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
解释:[4,9] 也是可通过的

提示:

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000
cpp 复制代码
class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
            unordered_set<int> s;
            for(int num: nums1)
            {
                s.insert(num);
            }
            unordered_set<int> res;
            for(int num: nums2)
            {
                if(s.find(num) != s.end())
                {
                    res.insert(num);
                }
            }
            vector<int> vectres;
            for(int num: res)
            {
                vectres.push_back(num);
            }
            return vectres;
    }
};
相关推荐
YuanDaima204820 小时前
双指针基础原理与题目说明
数据结构·人工智能·python·算法·leetcode·手撕代码
晨曦中的暮雨20 小时前
Java集合类型主要有哪些?以及各自原理
数据结构·算法
.柒宇.1 天前
力扣hot100之最大子数组和(Java版)
数据结构·算法·leetcode
6Hzlia1 天前
【Hot 100 刷题计划】 LeetCode 131. 分割回文串 | C++ 回溯算法基础切割法
c++·算法·leetcode
美式请加冰1 天前
子序列问题
数据结构·算法·leetcode
6Hzlia1 天前
【Hot 100 刷题计划】 LeetCode 1143. 最长公共子序列 | C++ 二维DP 与 哨兵技巧
c++·算法·leetcode
不才小强1 天前
查找算法详解:二分查找
数据结构·算法
Peregrine91 天前
数据结构 -> 顺序表
数据结构
动恰客流管家1 天前
动恰3DV3客流统计方案:赋能智慧公厕精细化运营
数据结构·人工智能·3d
XWalnut1 天前
LeetCode刷题 day10
数据结构·算法·leetcode