16 - 3Sum Closest

解法一 - Two Pointer

``````class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());

// Note:
// 1. Iterate to n-2 only
// 2. Need to skip same element to avoid duplicate triplets
int n = nums.size();
int closestSum, minDiff=INT_MAX;
for(int i=0; i<n-2; i++) {
// skip same element to avoid duplicate triplets
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
searchPair(nums, target, i+1, nums[i], closestSum, minDiff);
}

return closestSum;
}

private:
void searchPair(vector<int>& nums, int target, int start, int first, int& closestSum, int& minDiff) {
int l=start, r=nums.size()-1;

while(l<r) {
int sum = first+nums[l]+nums[r];
if(abs(sum-target) < minDiff) {
closestSum = sum;
minDiff = abs(sum-target);
}

if(sum == target) {minDiff = 0; closestSum = target; return;}
else if(sum > target) r--;
else if(sum < target) l++;
}
}
};
``````

``````class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int res, minDiff = INT_MAX;
sort(nums.begin(), nums.end());

for(int i=0; i<nums.size(); i++) {
int front = i+1;
int back = nums.size()-1;

while(front < back) {
int sum = nums[i] + nums[front] + nums[back];
int diff = abs(target - sum);

if(diff < minDiff) {
minDiff = diff;
res = sum;
}

if(sum < target) {
front++;
}
else if(sum > target) {
back--;
}
else {
return target;
}
}

while(i+1<nums.size() && nums[i+1] == nums[i])
i++;
}

return res;
}
};
``````