16. 3Sum Closest
16. 3Sum Closest
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).
1 /** 2 * @param {number[]} nums 3 * @param {number} target 4 * @return {number} 5 */ 6 var threeSumClosest = function(nums, target) { 7 8 //几乎和threeSum问题一样,但是这个问题有个好处就是只有唯一解 9 var len = nums.length; 10 var res = Number.MAX_VALUE; 11 var local = Number.MAX_VALUE; 12 nums.sort(function(a,b){ return a-b;}); 13 14 for(var i = 0;i < len;i++){ 15 16 //转成twoSum 问题 17 var temp = target - nums[i]; 18 19 var left = i + 1; var right = len - 1; 20 21 //双指针解法 22 while(left < right){ 23 24 var l = nums[left]; 25 var r = nums[right]; 26 var tempsum = l + r; 27 28 if(tempsum == temp){ 29 return target; 30 }else if(tempsum < temp){ 31 left++; 32 }else{ 33 right--; 34 } 35 36 37 if(Math.abs(tempsum+nums[i] - target) < local){ 38 39 local = Math.abs(tempsum+nums[i] - target); 40 res = tempsum+nums[i]; 41 } 42 43 44 45 } 46 47 } 48 49 return res; 50 51 };