原题链接
给含有n个元素的数组S,寻找出S中的三个元素,使其求和接近于所给的数字,target。并且返回这三个元素之和。你应该假设每一个输出只有一个确切的答案
例如, 所给数组为 S = {-1 2 1 -4}, 并且目标数字target = 1.
那么最接近目标数字的和是2. (-1 + 2 + 1 = 2).
public class Solution {
public int threeSumClosest(int[] num, int target) {
int result = num[0] + num[1] + num[num.length - 1];
Arrays.sort(num);
for (int i = 0; i < num.length - 2; i++) {
int start = i + 1, end = num.length - 1;
while (start < end) {
int sum = num[i] + num[start] + num[end];
if (sum > target) {
end--;
} else {
start++;
}
if (Math.abs(sum - target) < Math.abs(result - target)) {
result = sum;
}
}
}
return result;
}
}