3 Sum closest
*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).*
解题过程 :
之前有讲过把数组分为正数,负数,零三个数组来解决3Sum问题,看了一位牛人关于K sum问题的总结以后https://www.sigmainfy.com/blog/summary-of-ksum-problems.html,我对这个问题有了更深刻的认识。对于3 Sum问题,可以先将数组从小到大排序,然后固定一个数,分别从头尾取两个数与之相加,如果得到的sum比想要的结果大,那么为指针前移,否则头部指针后移。而对于3Sum Closest问题,和3 Sum问题相似,再加个变量记录最接近的数就可以了。
int threeSumClosest(vector<int>& nums, int target) {
int j = 0, lastIndex = nums.size()-2;
int k ;
int result;
int minSum = 10000;
sort(nums.begin(),nums.end());
for(int i =0; i< lastIndex; i++){
if(i>0 && nums[i] == nums[i-1]) continue;
k = lastIndex+1; j = i+1;
while(j<k){
int sum = nums[i]+nums[j]+nums[k];
if(sum <target ){
if(target - sum < minSum){
minSum = target - sum;
result = sum;
}
j++;
}
else if(sum >target){
if(sum - target < minSum){
minSum = sum - target;
result = sum;
}
k--;
}else {
return sum ;
}
}
}
return result;
}