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).
题目解析:
(1)首先将数组排序,然后利用2sum的基本方法。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void printVector(vector<int> &num)
{
vector<int>::iterator it = num.begin();
for(;it != num.end();it++)
{
cout << *it << " ";
}
cout << endl;
}
int threeSumClosest(vector<int> &num, int target) {
size_t len = num.size();
if(len < 3)
exit(-1);
vector<int>::iterator itBegin = num.begin();
vector<int>::iterator itEnd = num.end();
sort(itBegin,itEnd);
printVector(num);
int result = INT_MAX;
int resRe = 0;
for(size_t i = 0;i<len-2;i++)
{
size_t begin = i+1;
size_t end = len-1;
int residue = target - num[i];
while(begin < end)
{
if(result > abs(residue-(num[begin] + num[end])))
{
result = abs(residue-(num[begin] + num[end]));
resRe = num[i]+num[begin] + num[end];
}
if(num[begin] + num[end] < residue)
{
begin++;
}else if(num[begin] + num[end] > residue)
{
end--;
}else if(num[begin] + num[end] == residue)
{
return target;
}
}
}
return resRe;
}
int main(void)
{
vector<int> num;
num.push_back(-1);
num.push_back(2);
num.push_back(1);
num.push_back(-4);
int target = 1;
cout << threeSumClosest(num, target) << endl;
system("pause");
return 0;
}