题目描述
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
求解思路
-
因为题目答案中可能会有重复的三元组,所以需要对结果去重,但是发现集合set本身就不允许重复元素存在,所以采用HashSet来存储结果;
-
题目求解采用双指针法;
-
定义left和right,分别指向 i+1 和 nums.length-1 的元素,然后遍历nums,和之前一样;
-
这个地方需要注意当我们需要把普通的数组add进ArrayList需要做转换:Arrays.toList;
-
最后需要将HashSet转换为ArrayList,需要再做一次转换。
输入输出示例
代码
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Set<List<Integer>> res = new HashSet<>();
Arrays.sort(nums);
for(int i = 0; i < nums.length; i++){
int left = i + 1, right = nums.length - 1;
while(left < right){
if(nums[i] + nums[left] + nums[right] == 0){
res.add(new ArrayList<>(Arrays.asList(nums[i],nums[left],nums[right])));
left++;
right--;
}else if(nums[i] + nums[left] + nums[right] < 0){
left++;
}else{
right--;
}
}
}
List<List<Integer>> ress = new ArrayList<>(res);
return ress;
}
}