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.
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).
题目:找到三个数,这三个数的和与target最近接,返回这三个数的和;
思路:
先排序,然后左右各一指针,在sum小于目标值的时候左指针向右走,在sum大于目标值的时候右指针向左走。
代码:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
//找到与target最接近的三个数之和 并且三者的地址
vector<int>a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int target = 6;
int dist = INT_MAX;
sort(a.begin(), a.end());
int minsum;
vector<vector<int>::const_iterator> index;
for (vector<int>::const_iterator it = a.begin(); it != a.end(); it++)
{
vector<int>::const_iterator first = it + 1;
vector<int>::const_iterator last = a.end() - 1;
while (first < last)
{
int sum = *it + *first + *last;
//三个数的和对target进行判断
/*index.push_back(it);
index.push_back(first);
index.push_back(last);*/
if (sum>target)
{
if (abs(sum - target) < dist)
{
dist = abs(sum - target);
minsum = dist;
}
last--;
}
if (sum < target)
{
if (abs(sum - target) < dist)
{
dist = abs(sum - target);
minsum = dist;
}
first++;
}
else
{
dist = 0;
minsum = target;
break;
}
}
}
cout << minsum <<" "<<dist<< endl;
system("pause");
return 0;
}
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int sum=INT_MAX;
int minsum=0;
int nsum;
sort(nums.begin(),nums.end());
int i,j,k;
for(i=0;i<nums.size();i++)
{
j=i+1;
k=nums.size()-1;
while(j<k)
{
nsum=nums[i]+nums[j]+nums[k];
if(abs(nsum-target)<sum)
{
sum=abs(nsum-target);
minsum=nsum;
}
if(nsum-target<0)
{
j++;
}
else if(nsum-target>0)
{
k--;
}
else if((nsum-target)==0)
{
return target;
}
}
}
return minsum;
}
};