解答
简单一句话,先排序,然后固定第一个数a,再然后b、c只能从两边向中间靠(在a之后)。细节条件就是去重处理(i,start,end三个索引的去重都要考虑)
#include <vector>
#include <algorithm>
#include <math.h>
using namespace std;
// @lc code=start
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int n = nums.size();
//排序
sort(nums.begin(),nums.end());
//最小差值记录
int min = INT_MAX;
//结果值
int result = 0;
for (size_t i = 0; i < n; i++)
{
//跳过索引i的重复值
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
//左指针
int left = i+1;
//右指针
int right = n-1;
while (left<right)
{
int sum = nums[i]+nums[left]+nums[right];
//当三数之和与目标值一致时,直接返回
if(sum == target)
{
return sum;
}
//更新最小差值和结果值
if(abs(sum-target)<min)
{
min = abs(sum-target);
result = sum;
}
//三数之和大于目标值,右指针--
if(sum>target)
{
right--;
//跳过右指针的重复值
while (left<right&&nums[right]==nums[right+1])
{
right--;
}
}
//三数之和小于目标值,左指针++
else
{
left++;
//跳过左指针的重复值
while (left<right&&nums[left]==nums[left-1])
{
left++;
}
}
}
}
return result;
}
};