题目来源:
leetcode题目,网址:2215. 找出两数组的不同 - 力扣(LeetCode)
解题思路:
使用两个哈希集合保存两数组中的元素,然后寻找只在一个数组中出现的元素并按要求返回即可。
解题代码:
class Solution {
public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {
List<List<Integer>> res=new ArrayList<>();
Set<Integer> distinct1=new HashSet<>();
Set<Integer> distinct2=new HashSet<>();
Set<Integer> set1=new HashSet<>();
Set<Integer> set2=new HashSet<>();
for(int num:nums1){
set1.add(num);
}
for(int num:nums2){
set2.add(num);
if(!set1.contains(num) ){
distinct1.add(num);
}
}
for(int num:nums1){
if(!set2.contains(num)){
distinct2.add(num);
}
}
res.add(new ArrayList(distinct2));
res.add(new ArrayList(distinct1));
return res;
}
}
总结:
官方题解也是一样的思路,不过他在将元素加入哈希集合后,再次遍历的是哈希表而不是原数组。