1、问题描述
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
该题难点在于 要排除和为0重复的序列
2、解题思路
1)、将数组排序(原因下面步骤会提到)
2)、从数组的第一个元素开始进行循环,查找除该元素之外的剩余元素中有没有两元素之和等于该元素的负数,进而将问题转换为,查找两元素和为指定target的问题。
3)、由于数组已经是有序的,查找两元素和是否为target就很好办了,可由一个指向第一个元素(数组下标为low)的,和一个指向最后一个元素(数组下标high)的两个指针来向中间靠拢遍历查找有没有等于taget,此时由于数组有序,当nums[low]+nums[high] 等于target时 我们另low++ 继续查找,当大于target时另high--继续查找。该查找过程时间复杂度为N;
4)、题目中还有一个比较难办的问题是 怎么去除结果中重复的序列,为此我们可以在大循环的时候,不遍历值相等的元素,由于数组有序,若nums[i]==nums[i-1],我们跳过查找以nums[i]为target的计算机
3、代码
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ret = new ArrayList<>();
if (nums==null||nums.length==0) return ret;
Arrays.sort(nums);
for (int i = 0; i < nums.length-2; i++) {
if (i==0||i>0&&nums[i]!=nums[i-1]) {
int low = i+1,high = nums.length-1,sum = 0 -nums[i];
while(low<high){
if (nums[low]+nums[high] == sum) {
List<Integer> list = Arrays.asList(nums[i],nums[low],nums[high]);
ret.add(list);
while((low<high) && nums[low] == nums[low+1]) low++;
while((low<high) && nums[high] == nums[high-1]) high--;
low++;high--;
}else if(nums[low]+nums[high] <sum){
low++;
}else {
high--;
}
}
}
}
return ret;
}