Leetcode 3Sum Closest JS implementation

Source: Internet
Author: User
Tags abs diff

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; };

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.