Sort the array, for each a, search the sum of b,c from two ends to the middle, while updating the minimum distance between the target.
Similar solution could apply to 3Sum and 4Sum problems.
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
int min_dist = INT_MAX;
int result;
sort(num.begin(),num.end());
for(int i=0;i<num.size();i++) {
int j=i+1,k=num.size()-1;
while(j<k) {
int tmp = num[i]+num[j]+num[k];
int dist = tmp>target?tmp-target:target-tmp;
if(dist<min_dist) {
min_dist = dist;
result = tmp;
}
if(tmp>target) k--;
else j++;
}
}
return result;
}
};