题目描述
Given an array nums
of n integers, are there elements a, b, c in nums
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.
样例
Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
思路分析
受到启发之后才码出来的,首先排序,因为是三数相加,要遍历一遍数组,再采用夹逼法(夹逼法做这种数组题有种无敌的感觉)。过程中要避免遍历相同数的情况。
代码
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> list = new LinkedList<>();
for (int i = 0; i < nums.length-2; i++) {
if (i==0 || (i>0 && nums[i]!=nums[i-1])){
int low = i+1;
int high = nums.length-1;
int sum = 0 - nums[i];
while (low < high) {
if (sum == nums[low] + nums[high]){
list.add(Arrays.asList(nums[i],nums[low],nums[high]));
while(low<high && nums[low]==nums[low+1]){
low++;
}
while(low<high && nums[high]==nums[high-1]){
high--;
}
low++;
high--;
}
else if (sum < nums[low] + nums[high]){
high--;
}
else {
low++;
}
}
}
}
return list;
}
结果
后续修改版,做4sum题的时候,突然意识到此题还是遍历了很多无关元素,应该增加边界条件,即最小的三数和小于0时,直接退出循环。直接从beat62%升到98%~
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> list = new LinkedList<>();
for (int i = 0; i < nums.length-2; i++) {
if(nums[0]+nums[1]+nums[2] > 0){
break;
}
if(nums[nums.length-1]+nums[nums.length-2]+nums[nums.length-3] < 0){
continue;
}
if (i==0 || (i>0 && nums[i]!=nums[i-1])){
if (nums[i]+nums[i+1]+nums[i+2] > 0) {
break;
}
int low = i+1;
int high = nums.length-1;
int sum = 0 - nums[i];
while (low < high) {
if (sum == nums[low] + nums[high]){
list.add(Arrays.asList(nums[i],nums[low],nums[high]));
while(low<high && nums[low]==nums[low+1]){
low++;
}
while(low<high && nums[high]==nums[high-1]){
high--;
}
low++;
high--;
}
else if (sum < nums[low] + nums[high]){
high--;
}
else {
low++;
}
}
}
}
return list;
}
![](https://i-blog.csdnimg.cn/blog_migrate/30931a6f1e8c1029eac9f1f67c5ec0c8.jpeg)