这题和15题算法基本一模一样,就是判断相等改成的找到最相近的,
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
int sum=nums[0]+nums[1]+nums[2];
for(int i=0;i<nums.size();++i){
if(i==0||nums[i]!=nums[i-1]){
int left=i+1,right=nums.size()-1;
while(left<right){
int ans = nums[i]+nums[left]+nums[right];
if(abs(target-ans)<abs(target-sum)){
sum=ans;
if(sum==target)
return target;
}
(target-ans)>0?left++:right--;
}
}
}
return sum;
}
};