349. Intersection of Two Arrays
来源:互联网 发布:阿里云服务器上搭建svn 编辑:程序博客网 时间:2024/06/05 16:29
问题链接:https://leetcode.com/problems/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 unique.
- The result can be in any order.
思路:判断一个数是否在数组里,而不在交集的缓存数组里
问题:对于两个数组的非零元素的交集可以正常显示,但是若交集中含有0元素,则零元素无法呈现。
原因:数组在初始化时默认元素值均为0,所以再判断是否在缓存数组中时总是为true,导致0元素无法加入到缓存数组中。
解决办法:将缓存数组用-1填充,可以提交到LeetCode中,但是若测试用例含有-1则又通不过
public class Solution { public int[] intersection(int[] nums1, int[] nums2) { int len = Math.min(nums1.length, nums2.length); int[] temp = new int[len]; Arrays.fill(temp, -1); int index = 0; for(int i=0;i<nums1.length;i++) { if(isNumInArray(nums2,nums1[i]) && !isNumInArray(temp,nums1[i])) { temp[index++] = nums1[i]; } } return Arrays.copyOfRange(temp, 0, index); } private boolean isNumInArray(int[] nums, int num) { for(int i=0;i<nums.length;i++) { if(num == nums[i]) { return true; } } return false; }}
可以换一个思路,用set等容器实现:http://blog.csdn.net/ruobing2011/article/details/51514405
不能有重复数字,就想到使用数据类型Set。
逻辑原理:
- 数组一的数据存入hashset
- 遍历数组二如果set中存有该数据存入arraylist中,同时从set中remove该元素,防止多个元素重复
- 遍历list转变为array返回数据
public class Solution { public int[] intersection(int[] nums1, int[] nums2) { if(nums1==null || nums2==null) return null; if(nums1.length==0 || nums2.length==0) return new int[0]; Set<Integer> set=new HashSet<Integer>(); for(int i=0;i<nums1.length;i++){ set.add(nums1[i]); } List<Integer> res = new ArrayList<Integer>(); for(int i=0;i<nums2.length;i++){ if(set.contains(nums2[i])){ res.add(nums2[i]); set.remove(nums2[i]);//!!防止add到重复的数字 } } //遍历list成为数组返回 int[]a=new int[res.size()]; for(int i=0;i<res.size();i++){ a[i]=(int)res.get(i); } return a; } }
感想:思维不要僵化,要掌握各容器的特点,并根据需求灵活选用,而不是看到返回类型为数组在内部就一定要用数组
0 0
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays[][
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- Ruby on Rails学习笔记(4)--撤销生成的控制器/模型以及数据库迁移的回滚(撤销)
- Hibernate注解
- CFSwapInt32HostToBig() 基础解析
- CSP:使用CryptoAPI解码X509证书内容
- RabbitMQ消息队列(六):使用主题进行消息分发
- 349. Intersection of Two Arrays
- CAS单点登录技术原理
- Android开发笔记(一百三十二)矢量图形与矢量动画
- (6)Java 读写 hdfs文件或者目录
- Git 取消追踪某个文件
- SEAndroid策略分析
- 深入理解javascript原型和闭包(12)——简介【作用域】
- uva 11093 just finish IT
- OrangePi Zero在Armbian Ubuntu上安装Lubuntu-Desktop图形化桌面环境