Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where:
answer[0]is a list of all distinct integers innums1which are not present innums2.answer[1]is a list of all distinct integers innums2which are not present innums1.
Note that the integers in the lists may be returned in any order.
I have purposefully left print statement in there for debugging purpose.
class Solution {
public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
List<List<Integer>> ans = new ArrayList<>();
for(int i : nums2){
set2.add(i);
}
List<Integer> list = new ArrayList<>();
for(int i : nums1){
set1.add(i);
if(!set2.contains(i)) list.add(i);
}
System.out.println(list);
ans.add(list);
System.out.println(ans);
list.clear();
System.out.println(list);
for(int i : nums2){
if(set1.add(i)) {
list.add(i);
}
}
System.out.println(list);
ans.add(list);
System.out.println(ans);
return ans;
}
}
input:
nums1 = [1,2,3]
nums2 = [2,4,6]
output:
[1, 3]
[[1, 3]]
[]
[4, 6]
[[4, 6], [4, 6]]
Final value of ans is supposed to be [[1,3],[4,6]] instead of [[4, 6], [4, 6]].
Anyone one know why is it happening?
> ans` instead of adding 2 different List objects. Doing `and.add(list)` will **not** create a copy of `List list`. So any modification you do on that list will be visible everywhere that List is referenced.
– OH GOD SPIDERS Aug 14 '23 at 13:35