# Leetcode 3sum Closest

Source: Internet
Author: User

Given an array S of n integers, find three integers in S such so the sum is closest to a give n 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 is closest to the target is 2. (-1 + 2 + 1 = 2).This problem is similar to the upper body 3sum, except that it is necessary to use sum to compare with the target to determine whether the pointer +1, or-1, the same here need to first sort the elements, the code is as follows:`
`voidInsertsort2 (vector<int> &num) {    intNSize =num.size (); intj =0;  for(inti =1; i< nSize; ++i) {inttemp =Num[i];  for(j = i; j>0&& Temp < num[j-1] ; --j) {Num[j]= num[j-1]; } Num[j]=temp; }}intThreesumclosest (vector<int>& Nums,inttarget) {    intNSize =nums.size (); intsum =0; intDist =Int_max; intNprevdist =Int_max;    Insertsort2 (Nums); if(NSize <3)    {        return-1; }     for(inti =0; I!=nsize; ++i) {intp = i+1; intQ = nSize-1;  while(P <q) {sum= Nums[i] + nums[p] +Nums[q]; intTEMP = ABS (Sum-target); if(Temp <nprevdist) {Nprevdist=temp; Dist=sum; }            if(Sum >target) {                --Q; }            Else            {                ++p; }        }    }    returnDist;}`

We need to think more about how to use existing algorithms for reference.

Leetcode 3sum Closest

Related Keywords:

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.