问题链接: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;
}
}
感想:思维不要僵化,要掌握各容器的特点,并根据需求灵活选用,而不是看到返回类型为数组在内部就一定要用数组