两个数组nums1 和 nums2.
要找出nums1中有而nums2中没有的元素,放在list[0].
nums2中有而nums1中没有的元素,放在list[1].
最后返回list.
思路:
因为nums1和nums2的元素有值的限制,在-1000 ~ 1000之间。
可以定义2个长度为2000的boolean数组,记录nums1和nums2的每个数字是否出现。
最后比较2个boolean数组即可。
数组下标就是元素的值。
public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {
boolean[] bn1 = new boolean[2001];
boolean[] bn2 = new boolean[2001];
int n1 = nums1.length;
int n2 = nums2.length;
int i1 = 0;
int i2 = 0;
List<Integer> l1 = new ArrayList<>();
List<Integer> l2 = new ArrayList<>();
List<List<Integer>> res = new ArrayList<>();
while(i1 < n1 && i2 < n2) {
bn1[nums1[i1]+1000] = true;
bn2[nums2[i2]+1000] = true;
i1 ++;
i2 ++;
}
while(i1 < n1) {bn1[nums1[i1]+1000] = true; i1++;}
while(i2 < n2) {bn2[nums2[i2]+1000] = true; i2++;}
for(int i = 0; i < 2001; i++){
if(bn1[i] && !bn2[i]) l1.add(i-1000);
if(!bn1[i] && bn2[i]) l2.add(i-1000);
}
res.add(l1);
res.add(l2);
return res;
}