16.3Sum Closest (Two-Pointers)

时间:2020-12-25 07:07:19

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).
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int size = nums.size(); sort(nums.begin(), nums.end());
diff = INT_MAX;
for(int i = ; i < size-; i++){
if(i> && nums[i]==nums[i-]) continue;
find(nums, i+, size-, target-nums[i]);
if(diff == ) return target;
}
return target+diff;
} void find(vector<int>& nums, int start, int end, int target){
int sum;
while(start<end){
sum = nums[start]+nums[end];
if(sum == target){
diff = ;
return;
}
else if(sum>target){
do{
end--;
}while(end!=start && nums[end] == nums[end+]);
if(sum-target < abs(diff)) diff = sum - target;
}
else{
do{
start++;
}while(start!= end && nums[start] == nums[start-]);
if(target - sum < abs(diff)) diff = sum - target; //不能只在最后检查:可能会有这种情况,前一次sum>target,这次sum<target,而且下次就start==end,那么很可能前一次的sum比这次的sum更接近target
}
}
}
private:
int diff; //how much bigger is the sum
};