3Sum closest three numbers from the series and the closest to a given value

Source: Internet
Author: User

That is to ask min{target-a-b-c} a,b,c blog to Set S;

(a) The simplest course of action is to find out all the different three numbers and save to set, then use Target,target (+/-) I, I [0 ...]

Complexity can basically be considered O (n^3).

int Threesumclosest (vector<int> &num, int target) {     int n=num.size ();     if (n<3) return 0;     Unordered_set<int> sum;          for (int i=0, i<n; ++i) for     (Int. j=i+1;j<n; ++j) for     (int k=j+1; k<n;++k) {     int key = Num[i]+num[j]+num [K];     Sum.insert (key);     }     int lap=0;     while (true) {     if (Sum.find (TARGET+LAP)!=sum.end ()) return target+lap;     else if (Sum.find (TARGET-LAP)!=sum.end ()) return target-lap;     lap++;}     }


(b) with a simple solution, we naturally need to optimize it.

(1) The triple cycle must be able to kill, that is, the sum of two and their corresponding subscript stored in the map.

(2) Then use the number of arrays to map maps, initially a[i] +0, then a[i] +1, in turn, will be found.

(3) This is basically O (n^2).

int Threesumclosest (vector<int> &num, int target) {     int n=num.size ();     if (n<3) return 0;     Unordered_map<int,pair<int,int>> NUM0;     for (int i=0, i<n; ++i) for     (int j=i+1;j<n; ++j) {     int key = Target-num[i]-num[j];     Num0.insert (Make_pair (Key,make_pair (i,j));     }     int lap=0;     while (true) {for     (int i=0; i< num.size (); ++i) {     if (Num0.find (NUM[I]+LAP)!=num0.end ()      && i! =num0[num[i]+lap].first      &&i!=num0[num[i]+lap].second     )      return target-lap;          else if (Num0.find (NUM[I]-LAP)!=num0.end ()     && i!=num0[num[i]-lap].first      &&i!=num0[num[i ]-lap].second     )      return target+lap;     }     lap++;}     }


3Sum closest three numbers from the series and the closest to a given value

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.