HashSet 没有返回预期的输出
HashSet not returning expected output
我想存储唯一列表,所以我使用的是 HashSet。但是,我没有得到想要的输出。这是我的代码,你能告诉我哪里出了问题吗?
public List<List<Integer>> threeSum(int[] nums) {
Set<List<Integer>> res = new HashSet<>();
for(int i = 0; i< nums.length; i++){
int target = 0-nums[i];
Set<Integer> neg = new HashSet<>();
for(int j = i+1 ; j<nums.length; j++){
int rem = target - nums[j];
if(neg.contains(nums[j])){
res.add(new ArrayList<>(Arrays.asList(nums[i], rem, nums[j])));
}
else{
neg.add(rem);
}
}
}
System.out.println(res);
return new ArrayList<>(res);
}
这里我的数字是[-1,0,1,2,-1,-4]
。
我的输出是 [[-1,2,-1],[0,1,-1],[-1,0,1]]
。为什么我将 [0,1,-1]
和 [-1,0,1]
都放入 res 中,因为它们都包含相同的元素。我什么只有其中之一?我该怎么办?
您可以在添加到 Set
之前对 List
进行排序,这样它们的顺序就会相同。
来自 List.equals
的 Javadoc:
Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal.
因此,[0,1,-1]
和 [-1,0,1]
不相等,尽管包含相同的元素,因为它们的顺序不同。
解决这个问题的最简单方法是对列表进行排序:
res.add(Stream.of(nums[i], rem, nums[j]).sorted().collect(toList()));
我想存储唯一列表,所以我使用的是 HashSet。但是,我没有得到想要的输出。这是我的代码,你能告诉我哪里出了问题吗?
public List<List<Integer>> threeSum(int[] nums) {
Set<List<Integer>> res = new HashSet<>();
for(int i = 0; i< nums.length; i++){
int target = 0-nums[i];
Set<Integer> neg = new HashSet<>();
for(int j = i+1 ; j<nums.length; j++){
int rem = target - nums[j];
if(neg.contains(nums[j])){
res.add(new ArrayList<>(Arrays.asList(nums[i], rem, nums[j])));
}
else{
neg.add(rem);
}
}
}
System.out.println(res);
return new ArrayList<>(res);
}
这里我的数字是[-1,0,1,2,-1,-4]
。
我的输出是 [[-1,2,-1],[0,1,-1],[-1,0,1]]
。为什么我将 [0,1,-1]
和 [-1,0,1]
都放入 res 中,因为它们都包含相同的元素。我什么只有其中之一?我该怎么办?
您可以在添加到 Set
之前对 List
进行排序,这样它们的顺序就会相同。
来自 List.equals
的 Javadoc:
Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal.
因此,[0,1,-1]
和 [-1,0,1]
不相等,尽管包含相同的元素,因为它们的顺序不同。
解决这个问题的最简单方法是对列表进行排序:
res.add(Stream.of(nums[i], rem, nums[j]).sorted().collect(toList()));