[LeetCode][JavaScript]3Sum Closest

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).

https://leetcode.com/problems/3sum-closest/

 

 


 

 

与3Sum相同的思路http://www.cnblogs.com/Liok3187/p/4540921.html

每一轮先固定一个数,用双指针指向数组的头和尾。

如果目前三个数的和小于target,头指针++,否则尾指针--,直到指针碰到为止,记录最接近的结果。

 1 /**
 2  * @param {number[]} nums
 3  * @param {number} target
 4  * @return {number}
 5  */
 6 var threeSumClosest = function(nums, target) {
 7     var min = Infinity;
 8     var res = 0;
 9     nums = nums.sort(sorting);
10 
11     for(var i = 0; i < nums.length - 2; i++){
12         if(nums[i - 1] !== undefined && nums[i - 1] === nums[i]){
13             continue;
14         }
15         var curr = nums[i];
16         var m = i + 1;
17         var n = nums.length - 1;
18         while(m < n){
19             var tmp = Math.abs(nums[m] + nums[n] + curr - target);
20             if(tmp < min){
21                 min = tmp;
22                 res = nums[m] + nums[n] + curr;
23             }
24 
25             if(nums[m] + nums[n] + curr < target){
26                 m++;
27             } else {
28                 n--;
29             }
30         }
31     }
32     return res;
33 
34     function sorting(a, b){
35         if(a > b){
36             return 1;
37         }else if(a < b){
38             return -1;
39         }else{
40             return 0;
41         }
42     }
43 };

 

 

 

转载于:https://www.cnblogs.com/Liok3187/p/4609057.html

你可能感兴趣的:([LeetCode][JavaScript]3Sum Closest)