最接近的三数之和
给定一个包括 n 个整数的数组 nums
和 一个目标值 target
。找出 nums
中的三个整数,使得它们的和与 target
最接近。返回这三个数的和。假定每组输入只存在唯一答案。
示例:
输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
思路
和三数之和类似
解答
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int best = 10000;
for (int i = 0; i < nums.length; i++) {
if (i > 0 && nums[i - 1] == nums[i]) continue;
int j = i + 1, k = nums.length - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum == target) return sum;
if (Math.abs(target - sum) < Math.abs(target - best))
best = sum;
if (sum > target) {
int t = k - 1;
while(t > j && nums[t] == nums[k]) t--;
k = t;
} else {
int t = j + 1;
while (k > t && nums[t] == nums[j]) t++;
j = t;
}
}
}
return best;
}
}