class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int n=nums.size();
pair<int,int> res(INT_MAX,0);//分别存储差值,和
sort(nums.begin(),nums.end());
for(int i=0;i<n;i++)
for(int j=i+1,k=n-1;j<k;j++)
{
while(k-1>j&&nums[i]+nums[j]+nums[k-1]>=target)
//找出满足三数之和≥target,k的最小值
//试探k-1是否满足条件,需要保证k-1和j不重合
k--;
int sum=nums[i]+nums[j]+nums[k];
//此时k不一定保证三数之和≥target,也许找不到三数之和≥target,因此需要取绝对值
res=min(res,make_pair(abs(sum-target),sum));
if(k-1>j)
{
sum=nums[i]+nums[j]+nums[k-1];
res=min(res,make_pair(target-sum,sum));
//这里不用取绝对值,三数之和一定<target
}
}
return res.second;
}
};
标签:target,nums,int,三数,sum,16,res,LeetCode
From: https://www.cnblogs.com/tangxibomb/p/17217944.html