2019.1.27
题目描述:
Given an array nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
这题和求三数之和的那题思想基本上是一致的,都是利用双指针法来降低时间复杂度。
解法一:先将数组进行从小到大的排序,然后和求三数之和一样,先将一个数固定,接着双指针线性遍历后续数组,这里比求三数之和多的一步是要保证当前三数和跟给定值之间的差的绝对值最小,所以我们设一个temp记录差值的绝对值,一个res记录三数之和,遇到差值的绝对值更小的就更新temp与res。我们可以进行一些剪枝操作,比如说遇到三数之和等于target的时候,就直接返回target,因为差值的绝对值不可能比0还小了,还比如我们可以在排序后的数组中,可以跳过一些重复数字,具体参照我的另一篇博客https://blog.csdn.net/weixin_41637618/article/details/86654447
C++代码:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int temp=INT_MAX,res=0;
sort(nums.begin(),nums.end());
for(int k=0;k<nums.size();k++){
int i=k+1,j=nums.size()-1;
while(i<j){
if(nums[i]+nums[j]+nums[k]==target)
return target;
else if(nums[i]+nums[j]+nums[k]<target){
if(target-(nums[i]+nums[j]+nums[k])<temp){
res=nums[i]+nums[j]+nums[k];
temp=target-(nums[i]+nums[j]+nums[k]);
}
while(i<j&&nums[i]==nums[i+1])i++;
i++;
}
else if(nums[i]+nums[j]+nums[k]>target){
if(nums[i]+nums[j]+nums[k]-target<temp){
res=nums[i]+nums[j]+nums[k];
temp=nums[i]+nums[j]+nums[k]-target;
}
while(i<j&&nums[j]==nums[j-1])j--;
j--;
}
}
}
return res;
}
};
时间复杂度:O(n^2)
当然也可以用abs函数简化代码,思想是一致的,这里我就不贴代码了。