题目描述
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.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
题目解析
此题与15题3Sum类似。
先进行排序,构造i<\j<\k。
遍历 i 从1到cnt-2;
j和k的构造使用two-pointer法详细介绍见leetcode11题
代码
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int cnt = nums.size();
assert(cnt>=3);
sort(nums.begin(),nums.end());
int ans = nums[0]+nums[1]+nums[2];
for(int i = 0;i<cnt-2;++i)
{
if(i>1&&nums[i]==nums[i-1])
{
continue;
}
int j = i+1,k=cnt-1; //使用两指针法从两边向中间靠拢
while(j<k)
{
int sum = nums[i]+nums[j]+nums[k];
if(abs(sum-target)<abs(ans-target))
{
ans = sum;
}
if(sum == target)
{
return target;
}
if(sum<target)
{
++j;
}
else
{
--k;
}
}
}
return ans;
}
};