Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target.
Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
var threeSumClosest = function(nums, target) {
var n = 0;
var ans = 0;
var sum;
//排序
nums.sort((a,b) => a-b);
n = nums.length;
//如果數組中不多于3個元素,則返回所有元素和
if (nums.length <= 3) {
for (let i = 0;i < n;i++) {
ans += nums[i];
}
return ans;
}
//初始化記錄和的變量
ans = nums[0] + nums[1] + nums[2];
//遍歷每個元素
for (let i = 0; i < n-2; i++) {
//對于每個元素,我們首先將其后面的元素和整個的最后一個元素作為另外兩個元素
var j = i + 1;
var k = n - 1;
while (j < k) {
sum = nums[i] + nums[j] + nums[k];
//如果差距比當前記錄的小,更新記錄
if (Math.abs(target - ans) > Math.abs(target - sum)) {
ans = sum;
if (ans == target) return ans;
}
//如果和大,就把最后一個元素往前挪一個
//如果和小,就把第二個元素往后挪一個
(sum > target) ? k-- : j++;
}
}
return ans;
};