3Sum Closest
Total Accepted: 53147 Total Submissions: 195388 Difficulty: MediumGiven 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).
这道题的思路和之前的4Sum的思路一致,先把所有数增序排序,然后用三个指针,第一个指针从头到尾走形成第一层循环,第二个指针从第一个指针的下一个开始往后走,第三个指针从最后一个开始往前走,当第二个指针和第三个指针相遇时,就穷尽了在第一个指针固定的情况下,第二个数和第三个数的可能产生最接近值的组合情况,采用的策略是如果第二个数和第三个数相加的和大于target,则第三个指针往前走一个,因为之前已经按增序排序,所以第三个指针指向一个比之前小的值,如果第二个数和第三个数相加的和小于target,则第二个指针往后走一个,所以第二个指针指向一个比之前大的值。所以这个算法实际上是一个双重循环。
下面是完整程序代码:
#include <iostream>
#include <stdlib.h>
using namespace std;
int abs(int n)
{
return n>0?n:-1*n;
}
int cmp(const void *a, const void *b)
{
return *(int*)a - *(int*)b;
}
int threeSumClosest(int* nums, int numsSize, int target)
{
qsort(nums, numsSize, sizeof(int), cmp);
/*for(int i = 0; i < numsSize; i++)
{
cout<<nums[i]<<" ";
}*/
int optimal, difference = 10000000, p, q, tmp;
for(int i = 0; i < numsSize - 2; i++)
{
p = i + 1;
q = numsSize - 1;
while(p < q)
{
tmp = nums[i] + nums[p] + nums[q] - target;
if(abs(tmp) < difference)
{
difference = abs(tmp);
optimal = nums[i] + nums[p] + nums[q];
}
if(tmp < 0)
p++;
else if(tmp == 0)
return optimal;
else
q--;
}
}
return optimal;
}
int main()
{
int numsSize, *nums, target;
cout<<"Input the size of numbers:"<<endl;
cin>>numsSize;
nums = (int*)malloc(sizeof(int) * numsSize);
for(int i = 0; i < numsSize; i++)
{
cin>>nums[i];
}
cout<<"Input the target:"<<endl;
cin>>target;
cout<<endl<<threeSumClosest(nums, numsSize, target)<<endl;
}