Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
题目:给定数组和目标数,在数组中找到唯一三个数,这三个数的和接近于目标数,并返回这三个数的和
思路:把给定数组排序,小的在左边,大的在右边。因为题中求的是三个数的和,所以首先固定一个数(数组中的第一个数)然后依次递推。其余两个数一个是所剩数种最左边的,一个是最右边的,如果三个数之和大于目标数,就右边的索引左移,否则左边的索引右移。循环过程中,每次都把差值记录下来,保留最小差值的三个数和,最后输出。如果其中有刚好等于目标数的就直接输出。
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var threeSumClosest = function(nums, target) {
var numsArr = nums.sort(function(a,b){
return a-b;
});
var len = numsArr.length;
if(len === 3) return nums[0]+nums[1]+nums[2];
var res = 0;
var diff = Math.abs(numsArr[0]+numsArr[1]+numsArr[len-1]-target);
for(let i=0;i<len-2;i++){
var left = i+1;
var right = len-1;
while(left<right){
var res_temp = numsArr[i]+numsArr[left]+numsArr[right];
var diff_temp = Math.abs(res_temp-target);
if(diff_temp<=diff){
res = res_temp;
diff = diff_temp;
}
if(res_temp<target){
left++;
} else if(res_temp>target){
right--;
} else {
return res_temp;
}
}
}
return res;
};