C++:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int l, r;
int res = INT_MAX;
int ans = 0;
int n = nums.size();
for (int i=0; i<n-1;i++){
l = i + 1;
r = n - 1;
while(l<r){
int sum = nums[i] + nums[l] +nums[r];
int diff = abs(sum - target);
if (diff==0)
return target;
else if(sum > target)
r--;
else
l++;
if (diff < res){
res = diff;
ans = sum;
}
}
}
return ans;
}
};