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