第16题:3Sum Closest

来源:互联网 发布:如何查询淘宝商品类目 编辑:程序博客网 时间:2024/05/17 08:53

Given an array S of n integers, find three integers inS 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).


题目要求:从已知数组中找出三数之和最接近目标值的三个数(指其绝对值最接近)。


编程语言:javascript

解法:算法复杂度为O(n^2)  思路:思路基本同3Sum类似,只需将判断条件更换为比较绝对值大小即可。


/** * @param {number[]} nums * @param {number} target * @return {number} */var threeSumClosest = function(nums, target) {    var length = nums.length;        var closest = 9999;        //排序    nums.sort(function(x,y)    {        return x-y;    });        for(var i=0; i<length-2; ++i)    {        if(i>0 && nums[i] == nums[i-1])         {            continue;        }        var left = i+1;        var right = length-1;        while(left<right)        {            //记录当前3数和            var current_sum = nums[left] + nums[right] + nums[i];                                  if(target>current_sum)            {                if(target-current_sum < closest)                {                    closest = target - current_sum;                    result_sum = current_sum;                }                ++left;            }else if(target < current_sum)            {                                if(current_sum-target<closest)                {                    closest = current_sum - target;                    result_sum = current_sum;                }                --right;            }else{                return current_sum;            }        }    }    return result_sum;    };


0 0