题目链接:
力扣https://leetcode-cn.com/problems/find-the-difference-of-two-arrays/
【分析】用两个HashSet去重,然后分别遍历,可以以O(1)的复杂度查找在不在另一个集合中。
class Solution {
public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {
List<List<Integer>> ans = new ArrayList<>();
int i, n;
for(i = 0; i < 2; i++) ans.add(new ArrayList<>());
Set<Integer> s = new HashSet<>();
Set<Integer> t = new HashSet<>();
for(Integer it: nums1) s.add(it);
for(Integer it: nums2) t.add(it);
for(Integer it: s){
if(!t.contains(it)) ans.get(0).add(it);
}
for(Integer it: t){
if(!s.contains(it)) ans.get(1).add(it);
}
return ans;
}
}