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).跟三数求和为0题目接近,只是把指定数改变一下。思路还是一样的,为了遍历简单先排序,同样是三个指针,left,mid,right。
设置一个变量closest,为前三数之和。
开始两层循环。
三种情况:
1、nums[left]+nums[mid]+nums[right] == target
直接ruturn target就好
2、nums[left]+nums[mid]+nums[right] < target
说明三数之和还不够大,mid++。
—求绝对值,如果 abs(target - sum) < abs(target - closest) ,说明现在的和更接近target,closest = sum.
3、nums[left]+nums[mid]+nums[right] > target
说明三数之和还不够小,right--。
—求绝对值,如果 abs(target - sum) < abs(target - closest) ,说明现在的和更接近target,closest = sum.
4、遍历完毕,返回closest。
C++
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int length = nums.size();
int i,j,temp;
// 冒泡排序
for (i = 0; i < length - 1; i++) // 10个数,10 - 1轮冒泡,每一轮都将当前最大的数推到最后
{
for (j = 0; j < length -1 - i; j++) // 9 - i,意思是每当经过一轮冒泡后,就减少一次比较
if (nums[j] > nums[j+1])
{
temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
}
}
int closest = nums[0] + nums[1] + nums[2];
int left,mid,right;
for(left = 0;left < length;left++){
mid = left + 1;
right = length - 1;
while(mid < right){
int sum = nums[left] + nums[mid] + nums[right];
if(sum == target)
return target;
else if(sum < target){
mid++;
if(abs(target - sum) < abs(target - closest)){
closest = sum;
}
} else if (sum > target){
right--;
if(abs(target - sum) < abs(target - closest)){
closest = sum;
}
}
}
}
return closest;
}
};