LeetCode算法题-Intersection of Two Arrays(Java实现-四种解法)

Leetcode——Sort算法题 Easy 350. Intersection of Two Arrays II Given two arrays, write a function to compute their intersection. 正确版本: import java.util.ArrayList; import java.util.HashMap; public class Solution { publ... 阅读详情

这是悦乐书的第207次更新,第219篇原创

01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第75题(顺位题号是349)。给定两个数组,编写一个函数来计算它们的交集。例如:

输入:nums1 = [1,2,2,1],nums2 = [2,2]
输出:[2]

输入:nums1 = [4,9,5],nums2 = [9,4,9,8,4]
输出:[9,4]

注意:

  • 结果中的每个元素都必须是唯一的。

  • 结果可以是任何顺序。

本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。

02 第一种解法

暴力解法,直接使用两层循环,依次比较两个数组中的元素,如果相等,则将其存入HashSet中,这样可以保证不会出现重复元素,再将HashSet中的元素迭代放入数组,最后返回该数组。

此解法的时间复杂度是O(n^2),空间复杂度是O(n)。

public int[] intersection(int[] nums1, int[] nums2) {
    Set<Integer> set = new HashSet<Integer>();
    for(int i=0; i<nums1.length; i++){
        int tem = nums1[i];
        for (int j=0; j<nums2.length; j++) {
            if (tem == nums2[j]) {
                set.add(tem);
                break;
            }
        }
    }
    int[] result = new int[set.size()];
    int k = 0;
    for (int num : set) {
        result[k++] = num;
    }
    return result;
}

03 第二种解法

使用两个HashSet,先将其中一个数组的元素全部放入第一个HashSet中,然后迭代第二个数组,先判断第二个数组的每一个元素是否存在于第一个HashSet中,如果存在,将其放入第二个HashSet中,然后将第二个HashSet的元素迭代放入新数组中,最后返回。

此解法因为用到了HashSet的contains方法,因此时间复杂度最好情况是O(n),最坏情况是O(n^2),空间复杂度是O(n)。

public int[] intersection2(int[] nums1, int[] nums2) {
    Set<Integer> intersection = new HashSet<Integer>();
    Set<Integer> set = new HashSet<Integer>();
    for (int i : nums1) {
        set.add(i);
    }
    for (int i : nums2) {
        if (set.contains(i)) {
            intersection.add(i);
        }
    }
    int[] answer = new int[intersection.size()];
    int index = 0;
    for (int i : intersection) {
        answer[index++] = i;
    }
    return answer;
}

04 第三种解法

先将两数组排序,然后使用双指针,依次判断两数组中的元素是否相等,如果某个元素大于或小于另外一个元素,则将指针向后移动,如果相等,则将元素放入HashSet中,然后将HashSet中的元素迭代放入数组,最后返回。

因为使用Arrays类的sort方法,所以时间复杂度是O(n log(n)),空间复杂度是O(n)。

public int[] intersection3(int[] nums1, int[] nums2) {
    Set<Integer> set = new HashSet<>();
    Arrays.sort(nums1);
    Arrays.sort(nums2);
    int i = 0;
    int j = 0;
    while (i < nums1.length && j < nums2.length) {
        if (nums1[i] < nums2[j]) {
            i++;
        } else if (nums1[i] > nums2[j]) {
            j++;
        } else {
            set.add(nums1[i]);
            i++;
            j++;
        }
    }
    int[] result = new int[set.size()];
    int k = 0;
    for (Integer num : set) {
        result[k++] = num;
    }
    return result;
}

05 第四种解法

此解法和第一种解法类似,只是将内层循环换成了二分查找法,其他的思路都是一样的。

此解法的时间复杂度是O(nlogn),空间复杂度是O(n)。

public int[] intersection4(int[] nums1, int[] nums2) {
    Set<Integer> set = new HashSet<>();
    Arrays.sort(nums2);
    for (Integer num : nums1) {
        if (binarySearch(nums2, num)) {
            set.add(num);
        }
    }
    int i = 0;
    int[] result = new int[set.size()];
    for (Integer num : set) {
        result[i++] = num;
    }
    return result;
}

public boolean binarySearch(int[] nums, int target) {
    int low = 0;
    int high = nums.length - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (nums[mid] == target) {
            return true;
        }
        if (nums[mid] > target) {
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }
    return false;
}

06 小结

算法专题目前已连续日更超过两个月,算法题文章75+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

持续集成介绍及Jenkins自动化测试部署 学习持续集成及jenkins的自动化测试部署 阅读详情

相关推荐

别再乱提MR了!手把手教你配置GitLab的CI/CD与分支保护规则,让团队协作更丝滑

本文详细介绍了如何配置GitLab的CI/CD与分支保护规则,以优化团队协作流程。通过设置Protected Branches、MR流水线检查和自动化审批规则,有效防止不规范操作和合并冲突,提升开发效率与代码质量。特别强调MR(Merge Request)的正确使用,确保团队协作更丝滑。

weixin_28840591的博客 236

LeetCode--No.350--Intersection of Two Arrays II

Given two arrays, write a function to compute their intersection. Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. Note: Each element in the result should appear as ma

sophia_tone2w的博客 304

【Proteus】NE555纯硬件实现LED呼吸灯效果,附源文件,效果展示

本设计通过NE555与三极管的巧妙配合,仅用基础元件实现了呼吸灯效果。核心在于利用RC积分电路将PWM信号转换为控制电压,并通过负反馈动态调节占空比。Proteus仿真验证了方案的可行性,读者可进一步优化参数或扩展功能,探索更多硬件设计可能性。

2201_75797484的博客 2984

leetcode 1213 Intersection of Three Sorted Arrays

leetcode 1213 Intersection of Three Sorted Arrays Java solution using HashMap HashMap< Integer, Integer> map = new HashMap<>(); key是arrays的element, value是key的出现次数。 不可以有duplicate element ...

weixin_43876597的博客 334

FANUC机器人RSR与PNS功能深度解析及实战应用指南

本文深度解析了FANUC机器人RSR(远程程序启动)与PNS(程序号选择)两大核心功能。文章详细阐述了RSR的队列执行机制与PNS的二进制编码原理,提供了从硬件连接到参数配置的完整实战指南,并分享了混合使用策略与常见故障排除方法,旨在帮助工程师实现高效、稳定的生产线自动化程序调度。

neovim7hacker的博客 316

Trae CN 使用入门指南

【代码】Trae CN 使用入门指南。

weixin_42551921的博客 8776

leetcode(5): two array

1.leetcode#4. Median of Two Sorted Arrays 1.1问题描述 here are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time comple...

刘炫320的博客 590

从零构建Elasticsearch MCP代理:自然语言查询背后的技术揭秘

本文深入解析如何从零构建Elasticsearch MCP代理,实现自然语言查询的技术架构与实战应用。通过MCP协议与Elasticsearch的结合,系统能够将自然语言转换为精确的DSL查询,提升非技术用户的数据查询效率。文章详细介绍了核心架构、DSL生成引擎、端到端系统搭建及生产环境最佳实践,为开发者提供全面的技术指南。

lll78的博客 881

Intersection of Three Sorted Arrays

Given three integer arraysarr1,arr2andarr3sortedinstrictly increasingorder, return a sorted array ofonlytheintegers that appeared inallthree arrays. Example 1: Input: arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8] Output: [1,5] ...

leetcode 解题思路 321

Jetson AGX Orin 部署 JetPack:从依赖缺失到系统升级的完整排障指南

本文详细介绍了在Jetson AGX Orin开发板上部署JetPack SDK的完整排障指南,包括解决依赖缺失、系统升级和常见错误处理。通过确认硬件版本、配置正确的软件源、执行系统升级和安装核心组件等步骤,帮助开发者顺利完成JetPack的安装与配置,确保AI开发环境的稳定运行。

weixin_29172963的博客 160

GRCNN抓取网络学习2【自制Jacquard数据集训练】

请先完成【机械臂视觉抓取从理论到实战】,这样有利于下面操作的理解!然后第二步是GRCNN抓取网络1【Jacquard数据集等效抓取集制作】,有了自己的数据集输入到GRCNN中是三种文件,接下来就是准备训练GRCNN网络啦!grasps.txtRGB.png本文帮大家根据自制Jacquard数据集训练GRCNN抓取网络,其中包含数据格式的对齐,列举了常见的几种训练方法,相信能坚持到这里的都应该试试顺利了吧!接下来会针对GRCNN调优,期待一下下吧,那就别宁色你的三连。

vor234的博客 2802

Leetcode之Intersection of Two Arrays 问题

问题描述: Given two arrays, write a function to compute their intersection(交集). Note: Each element in the result must be unique.The result can be in any order. 示例: Example: Given nums1 = [1,

漫漫学习路 431

SAP_MM模块非限制库存转冻结库存

项目非限制 → 冻结事务码移动类型343影响库存不可用,不参与MRP常见用途质量问题封存、盘点冻结、待退货品通过本文,我们了解了 SAP 的[SAP_MM模块非限制库存转冻结库存]的基本概念和应用方法。希望这些信息能帮助您在实际工作中更好地使用 SAP 系统,提高工作效率和管理水平。更多SAP文章请点击更多SAP文章更新,大家一起学习进步!!!文章中如有错误。敬请指正!搜索公众号:SAP资料文库微信号:SPRO_PP时间:2025-10-14。

我小时候很黑的博客 592

LeetCode刷题:349. Intersection of Two Arrays&350. Intersection of Two Arrays II

LeetCode刷题:349. Intersection of Two Arrays&350. Intersection of Two Arrays II 原题链接: 349.Intersection of Two Arrayshttps://leetcode.com/problems/intersection-of-two-arrays/ 350.Intersection o...

梅森上校的博客 业精于勤荒于嬉,形成于思毁于随。 316

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

Leetcode日练笔记11 #350 #167 Intersection of Two Arrays II & Two Sum II - Input array is sorted

#350 Intersection of Two Arrays II Given two integer arraysnums1andnums2, returnan array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result inany order. 解题思路: 还是用回之...

Bittersweet_t的博客 1743

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

349. Intersection of Two Arrays

做这个题的时候才发现自己真的不懂java中的集合类,感觉没学过java....然后花了一点时间补了一些集合类的基本用法。 本题代码是我参考LeetCode上优秀题解写的,至少会用了ArrayList,HashSet,迭代器,foreach啥的。 源码: class Solution { public int[] set_intersection(HashSet<...

Ideaddxxpp的博客 364

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

leetcode 记录 349. Intersection of Two Arrays

此题的标签为:Binary Search、Hash Table、Two Pointers Sort 我的解法是直接用了hashset来做: public class Solution { public int[] intersection(int[] nums1, int[] nums2) { if(nums1.length==0||nums2.length==0)

万里晴空 2498

Intersection of Two Arrays II

Intersection of Two Arrays II Description Given two arrays, write a function to compute their intersection. Note - Each element in the result should appear as many times as it shows in both arra...

mcrwayfun,欢迎你 168

关于LeetCode中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 uni

zsy112371的专栏 1360

LeetCode 349: 两个数组的交集(Intersection of Two Arrays)解法汇总

文章目录题目我的解法降低时间复杂度其他语言参照javapython 题目 Given two arrays, write a function to compute their intersection. 我的解法 class Solution { public: vector<int> intersection(vector<int>& nums1, vecto...

Utopiabuntu的博客 276

leetcode Intersection of Two Arrays题解

题目描述: Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Ou...

leo_weile的博客 243

Leetcode 350. Intersection of Two Arrays II 数组交集2 解题报告

1 解题思想这道题和前两天的那个是一个系列的,只是那一个输出不能重复,而这一题重复了多少个,就输出多少个,所以先看下这个: Leetcode 349. Intersection of Two Arrays 解题报告 Python Java 做法,在Java上,就是把原来的HashSet转变成HashMap用来计数就可以了,剩下就很简单了2 原题Given two arrays, write a f

MebiuW的专栏 4642

LeetCode笔记:350. Intersection of Two Arrays II

找出两个数组中相同的数字(出现几次保留几次)

Minecraft 1889

LeetCode:Intersection of Two Arrays

  Intersection of Two Arrays     Total Accepted: 5682 Total Submissions: 12479 Difficulty: Easy   Given two arrays, write a function to compute their intersection. Example: Given nums1 = [1, 2...

walker lee 7800

【leetcode】【easy】349. Intersection of Two Arrays

349.Intersection of Two Arrays Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2] Example 2: Input: nums1 = [4,9,...

lemonade13的博客 151

LeetCode - 349. Intersection of Two Arrays

链接 349. Intersection of Two Arrays 题意 给定两个数组,求交集。 注意交集中的数是唯一的,顺序任意。 思路 将数组1存入set中 遍历数组2,只要set中有数组2中的数,便插入list list转为数组 代码 Java : public class Solution { public int[] intersection(int[] nums...

173
上一篇: LeetCode算法题-Reverse Vowels of a String(Java实现-四种解法)
下一篇: LeetCode算法题-Intersection of Two Arrays II(Java实现)
程序员小川
博客等级 码龄10年 47粉丝 305原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值