3Sum Closest
Given an array S of n integers, find three integers in S such so the sum is closest to a give n number, target. Return the sum of the three integers. You may assume this each input would has 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).
https://leetcode.com/problems/3sum-closest/
The same idea as the 3Sum http://www.cnblogs.com/Liok3187/p/4540921.html
Each round is fixed by a number, with a double pointer pointing to the head and tail of the array.
If the current three number is less than target, the head pointer + +, otherwise the tail pointer--until the pointer touches, records the closest result.
1 /**2 * @param {number[]} nums3 * @param {number} target4 * @return {number}5 */6 varThreesumclosest =function(nums, target) {7 varMin =Infinity;8 varres = 0;9Nums =nums.sort (sorting);Ten One for(vari = 0; i < nums.length-2; i++){ A if(Nums[i-1]!== undefined && nums[i-1] = = =Nums[i]) { - Continue; - } the varCurr =Nums[i]; - varm = i + 1; - varn = nums.length-1; - while(M <N) { + varTMP = Math.Abs (Nums[m] + nums[n] + Curr-target); - if(TMP <min) { +Min =tmp; Ares = Nums[m] + nums[n] +Curr; at } - - if(Nums[m] + nums[n] + Curr <target) { -m++; -}Else { -n--; in } - } to } + returnRes; - the functionsorting (A, b) { * if(A >b) { $ return1;Panax Notoginseng}Else if(A <b) { - return-1; the}Else{ + return0; A } the } +};
[Leetcode] [Javascript]3sum Closest