15. 三数之和
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
示例 2:
输入:nums = []
输出:[]
示例 3:
输入:nums = [0]
输出:[]
解析
固定一个位置,然后双指针碰撞
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
if(nums.length<3) return res;
for(int i = 0 ;i < nums.length-2;i++){
if(i>0 && nums[i]==nums[i-1]) continue;
int target = -nums[i];
int L = i+1;
int R = nums.length-1;
while(L<R){
int sum = nums[L]+nums[R];
if(sum==target){
List<Integer> tmp = new ArrayList<>();
tmp.add(nums[i]);tmp.add(nums[L]);tmp.add(nums[R]);
res.add(tmp);
while(L<R && nums[L]==nums[L+1]) L++;
L++;
while(R>L && nums[R]==nums[R-1]) R--;
R--;
}else if(sum>target){
R--;
}else{
L++;
}
}
}
return res;
}
}
注意:本文归作者所有,未经作者允许,不得转载