16. 3Sum Closest
Medium
131696FavoriteShare
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). 【题解】:这个题我是真的卡了好几天,主要是因为上一道题没用用指针的方式搜索也过了。。。可以去看我上一道题的题解,这个题,很关键的理解点是,要把数据进行排序,然后再固定一个数,另外两个数就可以通过指针的方式搜索了
这道题让我们求最接近给定值的三数之和,是在之前那道 3Sum 的基础上又增加了些许难度,那么这道题让我们返回这个最接近于给定值的值,即我们要保证当前三数和跟给定值之间的差的绝对值最小,所以我们需要定义一个变量 diff 用来记录差的绝对值,然后我们还是要先将数组排个序,然后开始遍历数组,思路跟那道三数之和很相似,都是先确定一个数,然后用两个指针 left 和 right 来滑动寻找另外两个数,每确定两个数,我们求出此三数之和,然后算和给定值的差的绝对值存在 newDiff 中,然后和 diff 比较并更新 diff 和结果 closest 即可,代码如下:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int diff = numeric_limits<int>::max();
int Final;
sort(nums.begin(),nums.end());
for(int i = ; i < nums.size()-; i++){
int tm1 = nums[i];
int left = i+; int right = nums.size()-;
while(left<right){
int sum = tm1+nums[left]+nums[right];
if(abs(target-sum) < diff){
diff = abs(target-sum) ;
Final = sum;
}
if(target==sum) return target;
else if(target < sum) right--;
else left++;
}
}
return Final;
}
};