3. 15_三数之和
/*
给定数组 nums = [-1, 0, 1, 2, -1, -4],
判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
*/
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ret = new ArrayList<>();
if(nums == null || nums.length < 3) return ret;
Arrays.sort(nums);
int len = nums.length;
List<Integer> ans = null;
for(int i=0; i < len-2; ++i){
if(nums[i] > 0) break;
if(i > 0 && nums[i] == nums[i-1]) continue;
int left = i+1,right = len-1;
while(left < right){
int sum = nums[i] + nums[left] + nums[right];
if(sum == 0){
ans = new ArrayList<>();
ans.add(nums[i]);
ans.add(nums[left]);
ans.add(nums[right]);
ret.add(ans);
while(left < right && nums[left] == nums[left+1])
left++;
while(left < right && nums[right] == nums[right-1])
right--;
right--;
left++;
}
else if(sum > 0){
right--;
}
else left++;
}
}
return ret;
}
}