描述
给定一个数字集合 S 以及一个数字 target,需要从集合中找出3个数字的和与这个 target的值最接近(绝对值最小)
样例
Input: S = [-1, 2, 1, -4], target = 1
Output: 2
思路
首先排序,之后确定一个数字的前提下,再利用双指针从两端向中间扫描,求
min | a+b+c - target|
,其中 a,b ,c 是 集合中数字。
代码
#include<iostream>
#include<string>
#include<vector>
#include <set>
#include <algorithm>
#include <cmath>
#include <climits>
using namespace std;
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
int maxdiff = INT_MAX;
int res = 0;
int len = nums.size();
for(int i=0;i<len-2;i++){
int start = i+1;
int end = len-1;
while(start<end){
int threeSum = nums[i] + nums[start] + nums[end];
int tempdiff = threeSum - target;
if(tempdiff == 0){
return threeSum;
}
else if(abs(tempdiff) < maxdiff){
maxdiff = abs(tempdiff);
res = threeSum;
}
if(threeSum > target){
end--;
}
else if(threeSum < target){
start++;
}
}
}
return res;
}
};
int main(){
// vector<int> nums{0,2,1,-3};
vector<int> nums{-1, 2, 1, -4};
int target = 1;
Solution ss;
cout<<ss.threeSumClosest(nums,target)<<endl;
}