给定两个0索引整数数组nums1
和nums2
,返回大小为2的列表答案,其中:
answer[0]
是nums1
中不存在于nums2
中的所有不同整数的列表。answer[1]
是nums2
中不存在于nums1
中的所有不同整数的列表。- 请注意,列表中的整数可以以任何顺序返回。*
我故意在那里留下print语句用于调试目的。
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;
}
}
输入:
nums1 = [1,2,3]
nums2 = [2,4,6]
产出:
[1, 3]
[[1, 3]]
[]
[4, 6]
[[4, 6], [4, 6]]
ans
的最终值应该是[[1,3],[4,6]]
而不是[[4, 6], [4, 6]]
。有人知道为什么会发生这种情况吗?
1条答案
按热度按时间pkwftd7m1#
这里你添加了对对象
list
的引用,但它是一个引用而不是一个副本,所以无论你在list
中做了什么修改,它也会反映在ans
中。如果你在System.out.println(list)
之后添加System.out.println(ans)
,你会看到
[[]]
。所以,引用的内容是空的。然后在脚本的结尾,你只需再添加一次引用到list
,所以很简单-无论你在list
中有什么,你在ans
中有两次。解决方案是添加对象的副本而不是引用-用途:而不是:
在你的代码中
如果你可以使用标准Java,你可以简化你的代码,比如: