Solution Accepted


#1

int Solution::threeSumClosest(vector &a, int tar) {
sort(a.begin(),a.end());
int n=a.size(),i,j,k;
int mi=INT_MAX,sum,ans;
for(i=0;i<n;i++){
j=i+1;
k=n-1;
while(j<k){
sum=a[i]+a[j]+a[k];
if(sum<tar){
if(mi>abs(sum-tar)){
mi=abs(sum-tar);
ans=sum;
}
j++;
}
else if(sum>tar){
if(mi>abs(sum-tar)){
mi=abs(sum-tar);
ans=sum;
}
k–;
}
else{
return tar;
}
}
}
return ans;
}
.