15. 三数之和:
题目链接 :15. 三数之和
题目:给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
思路:
1、定义三指针,每次循环内保持一个指针不动,其他两个指针在满足所求结果和的基础上移动。
2、去重规则很重要(详见代码中)
AC代码:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
/*
找出 不重复 和为0 三元组
特例:
1. nums.length<3
2. The sum of the sorted Array >0
*/
//构造默认的返回数组
List<List<Integer>> ans=new ArrayList();
if(nums==null||nums.length<3)
{
return ans;
}
Arrays.sort(nums);
for(int i=0;i<nums.length;i++)
{
//3. if nums[i]>0 the sum > 0
if(nums[i]>0)
{
break;
}
//去重规则2
if(i>0&&nums[i]==nums[i-1])
{
continue;
}
//再定义双指针满足遍历条件
int l=i+1,r=nums.length-1;
while(l<r)
{
int sum=nums[i]+nums[l]+nums[r];
if(sum==0){
//构建List
ans.add(Arrays.asList(nums[i],nums[l],nums[r]));
//去重规则2
while(l<r&&nums[l]==nums[l+1]) l++;
while(l<r&&nums[r]==nums[r-1]) r--;
l++;
r--;
}
//寻找满足条件的解
else if(sum>0)
{
r--;
}
else if(sum<0)
{
l++;
}
}
}
return ans;
}
}