LeetCode(四)——Intersection of Two ArraysII
来源:互联网 发布:个性头像制作软件 编辑:程序博客网 时间:2024/06/08 00:19
题目: Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
解析:这个题目和第二道题的区别在于两个集合的交集可以有重复元素,这里在检测到一个集合中有另一个集合的元素时要删除,而且最后生成的List的长度要根据里面元素的多少而定,不能大,如果大了,自动会进行初始化,初始化数据为0,如果两个集合输入为空,那么会导致最后输出的交集为0,结果错误(我就是这个原因导致可以编译,但是提交代码的时候会出现错误)
public class Solution { public int[] intersect(int[] nums1, int[] nums2) { List<Integer> list1 = new ArrayList<Integer>(); List<Integer> list2 = new ArrayList<Integer>();// int nums1[] = {1, 2, 3, 2};// int nums2[] = {2,2}; // if(nums1.length == 0 || nums2.length == 0) { // return []; // }// int len = nums1.length>nums2.length?nums1.length:nums2.length; for(int i:nums1) { list1.add(i); }// for(int i=0; i<nums2.length; i++) { // if(list1.contains(nums2[i])) { // list2.add(nums2[i]); // list1.remove(list1.indexOf(nums2[i])); // }// } for(int i:nums2) { if(list1.contains(i)) { list2.add(i); list1.remove(list1.indexOf(i)); } } int result[] = new int[list2.size()]; int i=0; for(int x:list2) { result[i] = x; System.out.println(x); i++; }// return list2.toArray(); return result; }}
坚持!
0 0
- LeetCode(四)——Intersection of Two ArraysII
- leetcode——Intersection of Two Arrays
- [leetcode]Intersection of Two Linked Lists —— 熟悉python
- Python学习——leetcode(Intersection of Two Linked Lists)
- LeetCode——Intersection of Two Linked Lists
- leetcode 160 —— Intersection of Two Linked Lists
- LeetCode题解——Intersection of Two Linked Lists
- LeetCode(2)——Intersection of Two Arrays
- leetcode——Intersection of Two Arrays II
- Leetcode——350. Intersection of Two Arrays II
- Leetcode——160. Intersection of Two Linked Lists
- Hold住Leetcode——Intersection of Two Arrays II
- Hold住Leetcode——Intersection of Two Arrays
- LeetCode——Intersection of Two Linked Lists
- #leetcode#Intersection of Two LinkedList
- [LeetCode] Intersection of Two Arrays
- LeetCode Intersection of Two Arrays
- LeetCode:Intersection of Two Arrays
- cookie,localStorage,sessionStorage三者的联系
- C#实现winform下图片的上传预览保存以及在桌面应用系统的应用
- C语言练习题每练 5 对于一个字符串,找到第一次重复出现的字符。
- 我对MVC和MVP的一些理解
- 匹配电话号码是不是有效
- LeetCode(四)——Intersection of Two ArraysII
- 如何去除ci框架中显示的index.php
- ES6新特性中的Module
- 安卓中向sd卡写文件
- Android Canvas drawArc方法介绍
- poj 2152 Fire 树形DP
- 安卓中创建别的应用程序可以读写的文件
- 局部内部类设置闹钟
- Android数据库框架ORMLite的学习笔记