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).
这几个sum题都很像,等写完全部的时候总结一下。
这题的想法和上一题几乎一样,closest来表示最近的那一个,剩下的还是把三个数字的和转换成两个数字。
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int closest=nums[0]+nums[1]+nums[2];
int min=abs(closest-target);
sort(nums.begin(),nums.end());
for(int k=0;k<nums.size()-2;k++)
{
int i=k+1;
int j=nums.size()-1;
while(i<j)
{
int sum=nums[k]+nums[i]+nums[j];
int newmin=abs(sum-target);
if(min>newmin)
{
min=newmin;
closest=sum;
}
if(sum<target)
i++;
else
j--;
}
}
return closest;
}
};