题目描述:
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/3s… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路: 排序 + 双指针
public static List<List<Integer>> threeSum1(int[] nums){
int n = nums.length;
List<List<Integer>> result = new ArrayList<>();
//0.首先对数组进行排序
Arrays.sort(nums);
//1.遍历每一个元素,作为三元组中最小的那个
for (int i=0;i<n;i++){
//1.1、如果当前的数已经大于0,直接退出循环
if (nums[i]>0) break;
//1.2、如果当前数据已经出现过,直接跳过
if (i>0 && nums[i] == nums[i-1]) continue;
//1.3、常规的情况下,以当前数作为最小数,定义左右指针
int lp = i+1;
int rp = n-1;
//左右指针不重叠,就继续移动指针
while(lp<rp){
int sum = nums[i] + nums[lp] + nums[rp];
//1.3.1、sum == 0的情况,证明找到了一组解
if (sum == 0){
result.add(Arrays.asList(nums[i],nums[lp],nums[rp]));
lp++;
rp--;
//如果移动之后的元素相同,直接跳过
while(lp<rp && nums[lp] == nums[lp-1]) lp++;
while(lp<rp && nums[rp] == nums[rp+1]) rp--;
}
//1.3.2、小于0,较小的数增大,左指针右移动
else if (sum < 0){
lp++;
}
//1.3.3、大于0,较大的数减小,右指针左移动
else{
rp--;
}
}
}
return result;
}