LeetCode 349. 两个数组的交集
发布日期:2021-06-30 18:35:12 浏览次数:2 分类:技术文章

本文共 775 字,大约阅读时间需要 2 分钟。

LeetCode 349. 两个数组的交集

题目

在这里插入图片描述

我的思路

先把 nums1 取出放入 Set 集合中

nums2 取出同时判断值在 nums1 集合中是否存在
存在则把集合存入一个新的 Set 集合中,由于哈希存储,不会出现重复情况
最后把值放入数组中返回

代码

class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
int index = 0; // Set 集合 存储 nums1 的值 Set num1 = new HashSet<>(); // 最终交集部分 Set
set = new HashSet<>(); for(int num : nums1) {
num1.add(num); } for(int num : nums2) {
// 判断 nums2 的值在 nums1 中是否存在 if (num1.contains(num)) {
set.add(num); } } // 最后把交集部分从 Set 中取出,放入数组返回 int[] arr = new int[set.size()]; for (int num : set) {
arr[index++] = num; } return arr; }}

转载地址:https://linjinp.blog.csdn.net/article/details/102461851 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode 739. 每日温度
下一篇:LeetCode 200. 岛屿数量

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月26日 03时04分34秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章