leetcode349: Intersection of Two Arrays
来源:互联网 发布:矩阵分解含义 编辑:程序博客网 时间:2024/06/14 03:08
要求:找出两个数组之间的交集。例如:
nums1=[1,2,2,1] nums2=[2,2] return[2]
注意:由于我们不知道有多少个元素会重复,所以不知道初始化的大小。考虑使用ArrayList,题目要求得出的结果中没有重复的元素,所以使用HashSet去除重复元素。最后需要将ArrayList转化为int型数组。注意考虑两个数组中有一个数组为空的情况,判断有一个数组为空时直接返回一个空数组。
public int[] intersection(int[] nums1, int[] nums2) {int l = 0;if (nums1.length > nums2.length)l = nums1.length;elsel = nums2.length;ArrayList list = new ArrayList();int[] fals = {};if (nums1.length == 0 || nums2.length == 0)return fals;int k = 0;for (int i = 0; i < nums1.length; i++) {for (int j = 0; j < nums2.length; j++) {if (nums1[i] == nums2[j]) {list.add(nums1[i]);k++;break;}}}HashSet h = new HashSet(list);list.clear();list.addAll(h);int rl = list.size();int[] result = new int[rl];for (int i = 0; i < rl; i++)result[i] = Integer.parseInt(String.valueOf(list.get(i)));return result;}
0 0
- leetcode349: Intersection of Two Arrays
- Leetcode349. Intersection of Two Arrays
- Leetcode349. Intersection of Two Arrays
- Leetcode349. Intersection of Two Arrays
- LeetCode349. Intersection of Two Arrays
- LeetCode349 Intersection of Two Arrays
- leetcode349~Intersection of Two Arrays
- leetcode349. Intersection of Two Arrays
- leetcode349. Intersection of Two Arrays
- Leetcode349 - Intersection of Two Arrays(two pointers)
- LeetCode349. Intersection of Two Arrays我的做法
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- @RenderBody、@RenderSection、@RenderPage、Html.RenderPartial、Html.RenderAction的作用和区别
- 新闻推荐系统之朴素贝叶斯分类器文本分类
- 自动更新覆盖安装的模板代码
- 第一个network的代码实现基于mnist数据集
- ServletContext域对象和资源路径读取问题
- leetcode349: Intersection of Two Arrays
- codeforces-337【C思维,贪心】
- 洛谷1120小木棍
- JQuery技术初探之二级联动的设计与实现
- 搬家送书咯!
- MVP模式学习———登陆例子
- TFT-LCD驱动程序设计(系列一)
- 第6节--python数据类型--string
- stm32学习的日子-构建库函数雏形(第1节)—寄存器结构体定义控制点亮G0Kitv2.1 LED2和LED4