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).
对于一个数组S,求数组中三个数a、b、c的和,使之最接近target。将问题抽象化为,求一个min使得:
\[min = arg \ min | \ target - min \ | \quad s.t. \quad min =a+b+c\]
即求出使得$| ?target - min ?| $时min的值。
三指针法,见题[15]。三指针方法的关键是:
每次只移动一个指针
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(),nums.end()); //对数组排序
int min=nums[0]+nums[1]+nums[2]; //初始化最小值
for(int pBegin=0;pBegin<nums.size();pBegin++){
int pMid = pBegin+1;//中间指针
int pEnd=nums.size()-1;//尾指针
int sub=target-nums[pBegin];
while(pMid<pEnd){
if(abs(sub-nums[pMid]-nums[pEnd]) < abs(target-min)) //更新最接近target时的和
min = nums[pBegin]+nums[pMid]+nums[pEnd];
if(nums[pMid]+nums[pEnd] == sub){
return target;
}
else if(nums[pMid]+nums[pEnd] > sub){
pEnd--;
}
else{
pMid++;
}
}
}
return min;
}
原文:https://www.cnblogs.com/Jessey-Ge/p/10993493.html