題目描述
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).
思路
目的:找到三個數(shù)的和最接近target。
排序亚皂,從小到大,使與target之差值越來越小。i,j最小,k最大昔园,然后去找合適值蔓榄。
- 如果三個數(shù)之和大于target,判斷之差是否比目前最小差更小默刚,更小就更新結(jié)果以及最小差甥郑,同時將j增大。
- 反之同理荤西。
- 相等就是了澜搅。
代碼
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
if (nums.size() < 3)
{
return -1;
}
int res = 0;//最后答案
int distance = INT_MAX;//總的最近的差,包括大的和小的
int i, j, k;
sort(nums.begin(),nums.end());//先排序
for (i = 0; i < nums.size() - 2; i++)
{
j = i + 1;
k = nums.size() - 1;
while (j < k)
{
int temp = nums[i] + nums[j] + nums[k];
int temp_distance;
if (temp < target)//說明太小了邪锌,要變大
{
temp_distance = target - temp;//當(dāng)前三個值與target的差
if (temp_distance < distance)//更接近了可以進(jìn)行更新
{
res = temp;
}
j++;
}
else if(temp > target)
{
temp = nums[i] + nums[j] + nums[k];
temp_distance = temp - target;
if (temp_distance < distance)
{
res = temp;
}
k--;
}
else
{
temp = nums[i] + nums[j] + nums[k];
res = temp;
}
}
}
}
};