题目
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例1: nums = [-1, 0, 1, 2, -1, -4],输出 [[-1, 0, 1], [-1, -1, 2]]
示例2:nums=[0, 0, 0],输出 [[0,0,0]]
示例3:nums=[-2, 0, 0, 2, 2],输出 [[-2, 0, 2]]
使用二分法查找,效率会要高。首先将数组进行排序,数组长度小于3或者第一个数大于0或者最后一个数小于0,则不存在该三元组。然后用指针left,right依次去查找满足该条件的三元组,记得去重处理。
public List<List<Integer>> threeSumMethod(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
if (!(nums.length < 3 || nums[0] >0 || nums[nums.length-1] < 0)){
for (int i=0; i<nums.length; i++){
if (nums[i] > 0){
break;
}
if (i>0 && nums[i-1] == nums[i]){
continue;
}
int left = i+1;
int right = nums.length-1;
while (left < right){
if (nums[i] + nums[left] + nums[right] == 0){
List<Integer> threenums = new ArrayList<>();
threenums.add(nums[i]);
threenums.add(nums[left]);
threenums.add(nums[right]);
result.add(threenums);
while (left < right && nums[left] == nums[left+1]){
left++;
}
while (left < right && nums[right] == nums[right-1]){
right--;
}
left++;
right--;
}else if (nums[i] + nums[left] + nums[right] > 0){
right--;
}else {
left++;
}
}
}
}
return result;
}