最接近的三数之和
题目:
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。
找出 nums 中的三个整数,使得它们的和与 target 最接近。
返回这三个数的和。假定每组输入只存在唯一答案。
思路:
1.排序
2.三数之和大于target--->r--
3.三数之和小于target--->l++
4.根据与target的大小比较来判断走向,然后更新左右索引,最后返回这三个数的和。
public static int threeSumClosest(int[] nums, int target) {
int len = nums.length;
int ans = nums[0] + nums[1] + nums[2];//存储结果
Arrays.sort(nums); // 排序
//三数之和大于target--->r--
//三数之和小于target--->l++
//根据与target的大小比较来判断走向,然后更新ans(差值),返回这三个数的和
for (int i = 0; i < len-2 ; i++) {
int L = i+1;
int R = len-1;
while(L < R){
int sum = nums[i] + nums[L] + nums[R];
if(sum == target){//说明刚好相等,这个时候一定是最优解
ans = sum;
break;
} else if (sum < target){
ans = Math.abs(sum-target) > Math.abs(ans-target)? ans:sum;
while (L<R && nums[L] == nums[L+1]) L++;
L++;
} else {
ans = Math.abs(sum-target) > Math.abs(ans-target)? ans:sum;
while (L<R && nums[R] == nums[R-1]) R--;
R--;
}
}
}
return ans;
}
阿里云成长空间 794人发布