给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
2.题目示例
示例 1:
输入:nums =[-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
示例 2: 输入:nums = [] 输出:[]
示例 3: 输入:nums = [0] 输出:[]
3.提示
0 <= nums.length <= 3000
105 <= nums[i] <= 105
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! 我们实际上需要找到三个数x y和z使它们加起来等于给定的值。如果我们固定其中一个数字,比如x,我们就剩下了两个和的问题!
For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? 对于二和问题,如果我们固定一个数字,比如x,我们必须扫描整个数组来找到下一个数字y,它的值是- x 其中value为输入参数。我们能不能改变数组让搜索变得更快?
The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search? 二和运算的第二种思路是,在不改变数组的情况下,我们可以使用额外的空间吗?比如用哈希映射来加速搜索?
nums =[-1,0,1,2,-1,-4]--------------------------------[-4,-1,-1,0,1,2] a+b+c!=0
↑ ↑ ↑
a b c
[-4,-1,-1,0,1,2] a+b+c!=0
↑ ↑ ↑
a b c
[-4,-1,-1,0,1,2] a+b+c!=0
↑ ↑ ↑
a b c
[-4,-1,-1,0,1,2] a+b+c!=0
↑ ↑ ↑
a b c
[-4,-1,-1,0,1,2] a+b+c=0
↑ ↑ ↑
a b c
。。。。。。。。。。
4.2 业务代码
classSolution{publicstatic List<List<Integer>>threeSum(int[] nums){
List<List<Integer>> ans =newArrayList();int len = nums.length;if(nums == null || len <3)return ans;
Arrays.sort(nums);// 排序for(int i =0; i < len ; i++){if(nums[i]>0)break;// 如果当前数字大于0,则三数之和一定大于0,所以结束循环if(i >0&& nums[i]== nums[i-1])continue;// 去重int L = i+1;int R = len-1;while(L < R){int sum = nums[i]+ nums[L]+ nums[R];if(sum ==0){
ans.add(Arrays.asList(nums[i],nums[L],nums[R]));while(L<R && nums[L]== nums[L+1]) L++;// 去重while(L<R && nums[R]== nums[R-1]) R--;// 去重
L++;
R--;}elseif(sum <0) L++;elseif(sum >0) R--;}}return ans;}}