Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
std::sort(nums.begin(), nums.end());
int len = nums.size();
long bestDist = LONG_MAX, bestSum = target;
if(len <= 2)
return 0;
for(int i = 0; i < len-2; i++)
{
int a = nums[i];
if(i > 0 && nums[i-1] == a)
continue;
for(int j = i+1, k = len-1; j<k;)
{
int b = nums[j];
int c = nums[k];
int dist = abs(a+b+c - target);
if(dist < bestDist){
bestDist = dist;
bestSum = a+b+c;
}
if(a+b+c - target > 0)
k--;
else
j++;
}
}
return bestSum;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment