Question:
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).
Solution:
class Solution {
public:
int ctar = 0;
int diff = 0x3f3f3f3f;
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
int len = nums.size();
for(int i = 0; i < len ; i++){
find(nums, i + 1 , len -1 , nums[i] , target);
}
return ctar;
}
void find(vector<int> v, int s , int e , int data ,int tar){
while(s < e){
int tmp = v[s] + v[e] + data;
int ddiff = tar - tmp;
if(abs(ddiff) < abs(diff)){
diff = ddiff;
ctar = tmp;
}
if(tmp == tar ){
diff = 0;
ctar = tar;
return;
}
else if(tmp < tar){
s++;
}
else if(tmp > tar){
e--;
}
}
}
};