JAVA版本
思路:因为比较两个数组中的相同元素,我们可以使用set来存储,去掉相同的元素之后,在利用这个集合来对第二个数组中的元素来进行对比。如果该数组中有与集合中相同的数时,将这个数组中的值添加到新的集合中。
最后再将集合转变为数组。
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if(nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
return new int[0];
}
Set<Integer> set1 = new HashSet<>();
Set<Integer> resSet = new HashSet<>();
//遍历数组1
for (int i : nums1) {
set1.add(i);
}
//遍历数组2的过程中判断哈希表中是否存在该元素
for (int i : nums2) {
if (set1.contains(i)) {
resSet.add(i);
}
}
//再将set转化为数组
int[] arr = new int[resSet.size()];
int j = 0;
for(int i : resSet){
arr[j++] = i;
}
return arr;
}
}
笔者认为,本题最重要的是集合转换为数组的方法。思路较简单,多练习即可。