题目
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[-1, 0, 1],
[-1, -1, 2]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
自己解题:
不断使用二分查找,超时了;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static java.util.Arrays.binarySearch;
/**
* 三个数之和
*/
public class SumOfThree {
public static void main(String[] args) {
// int[] nums = {-4, -1, -1, 0, 1, 2};
int[] nums = {-4,-2,1,-5,-4,-4,4,-2,0,4,0,-2,3,1,-5,0};
List<List<Integer>> res = threeSum(nums);
int i = 0;
for (List<Integer> sigleRes : res) {
for (Integer num : sigleRes) {
if (i % 3 == 2 && i != 0 ){
System.out.println(num);
}else{
System.out.print(num + " ");
}
i++;
}
}
}
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
// 从小到大排序
Arrays.sort(nums);
if (nums.length != 0 && nums[0] <= 0) {
// 如果最小的数字小等于0
// 只遍历小等于于0的数字,双指针
int left = 0;
int right = nums.length - 1;
while (left < right && nums[left] <= 0) {
// 首尾两数之和
int twoSum = nums[left] + nums[right];
// 寻找两数之和相反数
int midIndex = myBinarySearch(nums, left + 1, right, 0 - twoSum);
if (midIndex == nums.length << 1){
// 没找到
right--;
}else {
// 找到了
List<Integer> singleRes = new ArrayList<Integer>();
singleRes.add(nums[left]);
singleRes.add(nums[midIndex]);
singleRes.add(nums[right--]);
if(!res.contains(singleRes)) {
res.add(singleRes);
}
}
// 当前left的组合找完了,left自增,right变为数组末尾
if (right == left + 1 || (nums[right] == 0 && twoSum < 0)) {
left++;
right = nums.length - 1;
}
}
}
return res;
}
private static int myBinarySearch(int[] a, int fromIndex, int toIndex,int key) {
int low = fromIndex;
int high = toIndex - 1;
while (low <= high) {
int mid = (low + high) >> 1;
int midVal = a[mid];
if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return a.length << 1; // key not found.
}
}
2、将“查找两数之和的相反数”的思路转换为“遍历数组时候直接检查条件 ”
代码
List<List<Integer>> ans = new ArrayList();
int len = nums.length;
if(nums == null || len < 3) return ans;
Arrays.sort(nums); // 排序
for (int i = 0; i < len ; i++) {
if(nums[i] > 0) break; // 如果当前数字大于0,则三数之和一定大于0,所以结束循环
if(i > 0 && nums[i] == nums[i-1]) continue; // 去重
int L = i+1;
int R = len-1;
while(L < R){
int sum = nums[i] + nums[L] + nums[R];
if(sum == 0){
ans.add(Arrays.asList(nums[i],nums[L],nums[R]));
while (L<R && nums[L] == nums[L+1]) L++; // 去重
while (L<R && nums[R] == nums[R-1]) R--; // 去重
L++;
R--;
}
else if (sum < 0) L++;
else if (sum > 0) R--;
}
}
return ans;
总结