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).
- 題目大意
與上一道題基本一樣,只不過這回是找到3個(gè)數(shù),使他們的和與給定的target最為相近御滩。
算法上與上一題類似概说,只不過我們不再需要去掉重復(fù)的數(shù)字
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var threeSumClosest = function(nums, target) {
nums.sort((a, b) => a - b);
let result = Number.MAX_VALUE;
for (let i = 0; i < nums.length - 2; i++) {
let j = i + 1;
let k = nums.length - 1;
while (j < k) {
let sum=nums[i]+nums[j]+nums[k];
if (Math.abs(result-target)>Math.abs(sum-target)) { //判斷是否相近
result = sum;
if (result === target) return result; //當(dāng)找到3個(gè)數(shù)的和與target相同時(shí) 直接退出
}
if (sum>target) k--;
else
j++;
}
}
return result;
};