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).Array Two Pointers
Solution in C++:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int result=0;
if(nums.size()<=3){
for(int i=0; i<nums.size(); i++) result+=nums[i];
return result;
}
sort(nums.begin(), nums.end());
result = nums[0]+nums[1]+nums[2];
int sum;
for(int i=0; i<nums.size()-2; i++){
int start = i+1, end = nums.size()-1;
while(start<end){
sum = nums[i]+nums[start]+nums[end];
if(sum==target) return target;
else if(sum<target) start++;
else end--;
result = abs(result-target)<=abs(sum-target)?result:sum;
}
while(nums[i+1]==nums[i]&&i+1<nums.size()) i++;
}
return result;
}
};