题意
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
给定一个数组及一个目标值,找出三个数,使它们的和与目标值的差值最小,输出它们的和。
解法
与上一题3Sum一样,遍历第一个数,然后用双指针算法遍历剩下两个数,随时比较它们与目标值的差值。
class Solution
{
public:
int threeSumClosest(vector<int>& nums, int target)
{
sort(nums.begin(),nums.end());
int diff = 0x7fffffff;
int ans = 0;
for(int i = 0;i < nums.size();i ++)
{
int j = i + 1;
int k = nums.size() - 1;
while(j < k)
{
int sum = nums[i] + nums[j] + nums[k];
if(abs(sum - target) < diff)
{
diff = abs(sum - target);
ans = sum;
}
if(sum < target)
j ++;
else
k --;
}
}
return ans;
}
};