Given an array S of n integers, find three integers in s such so the sum is closest to a Given number, target. Return the sum of the three integers. You may assume this each input would have exactly one solution.
For example, given array S = {-1 2 1-4}, and target = 1.
The sum is closest to the target is 2. (-1 + 2 + 1 = 2).
Comparison function functions Sortnum (a,b) {return a-b; var threesumclosest = function (Nums, target) {switch (nums.length) {case 0:re
Turn 0;
Case 1:return Nums[0];
Case 2:return Nums[0]+nums[1];
Default:break;
} var k=nums.length-1; var arrnum=nums.sort (Sortnum); First the array of the order of Var currentsum=arrnum[0]+arrnum[1]+arrnum[2];
Given the initial comparison value Var Closesum=currentsum;
var diff =math.abs (Currentsum-target);
for (var i = 0; i < k-1 i++)////Set first number first and the last number, if three number of and greater than the target value, then k minus 1; if less than the target value plus 1;j and K values are equal, then I plus 1, into the outer layer next cycle, K value must be reset; K=nums.length-1;
K to reset for (var j = i+1 J < K;)
{currentsum = Arrnum[i] + arrnum[j] + arrnum[k];
if (currentsum = = target) {return currentsum; } if (Math.Abs (currentsum-target) < diff) {closesum = Currentsum;
diff = Math.Abs (currentsum-target);
} if (Currentsum < target) {j + +;
else {k--;
}} return closesum; };