Leetcode (3Sum Closest)

Source: Internet
Author: User

Topic

Given an array S of n integers, find three integers in S such, the sum was closest to a Given 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 that is closest to the target is 2. (-1 + 2 + 1 = 2).
Analysis

This question is very similar to the previous one. The sum of the ternary elements closest to the target value in an integer array sequence is obtained.
The solution to this problem is a three-layer traversal, a summation comparison, but it is obvious that the time-out exception will inevitably occur when Leetcode commits. So you have to find another method, the AC code of this topic comes from the reference, here to express our thanks.

Time Limit exceeded code
classSolution { Public://Method 1:3-level exhaustive, timeout exception    intThreesumclosest ( vector<int>& Nums,intTarget) {intLen = Nums.size ();if(Len <3)        {return 0; }intclosest = nums[0] + nums[1] + nums[2]; for(inti =1; I < len-2; i++) {//First go to the re-operation            if(Nums[i] = = Nums[i-1])Continue; for(intj = i +1; J < Len-1; J + +) {if(Nums[j] = = Nums[j-1])Continue; for(intK = j +1; K < Len; k++) {if(Nums[k] = = Nums[k-1])Continue;intsum = Nums[i] + nums[j] + nums[k];if(sum = = target) {closest = sum; Break; }//if                    Else    if(ABS(Sum-target) <ABS(Closest-target))                    {closest = sum; }//elif                    Else                        Continue; }//for}//for}//for        returnClosest }int ABS(intA) {returnA >0? A:0-A; }};
AC Code
 class solution { Public:intThreesumclosest (vector<int>& Nums,intTarget) {size_t size = nums.size ();if(Size <3) {cout <<"num size must bigger than there!"<< Endl;return 0; } sort (Nums.begin (), Nums.end ());//For the following process must be sorted in advance, similar to binary search        intresult =0;//Record the final result        intDistance = numeric_limits<int>::max ();//Signed int        int sum=0;//Intermediate resultssize_t i =0, j = i +1, k = Size-1; for(i =0; I < size-2; i++)//The first element of the ternary group is traversed one time, with a range of [0...n-3]{//de-duplication to avoid repeated calculations, if and last the same skip            if(I >0&& Nums[i] = = Nums[i-1])            {Continue; } j = i +1;//After the first element of the ternary group is selected, the second element is examined from the next position of the first elementK = Size-1;//After the first element of the ternary group is selected, the third element is examined from the end of the array             while(J < K)The last two elements of the ternary group use the left and right approximation to skip efficiency, and after the first element is selected, all subsequent elements are examined only once.{sum= Nums[i] + nums[j] + nums[k];if(sum= = target)///existence distance of the nearest 0 is returned directly, otherwise the exhaustive selection is not 0 minimum distance{return sum; }Else if(sum< target) {if(Target-sum) (< distance) {result =sum; Distance = target-sum; } j = j +1;//Avoid repeated calculations if you skipped with the last time                    if(Nums[j] = = Nums[j-1]) {j = j +1; }                }Else if(sum> Target) {if((sum-target) < distance) {result =sum; Distance =sum-Target; } k = k-1;//Avoid repeated calculations if you skipped with the last time                    if(Nums[k] = = Nums[k +1]) {k = k-1; }                }            }        }returnResult }};

GitHub test Program source code

Leetcode (3Sum Closest)

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.