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).
int threeSumClosest(int* nums, int numsSize, int target) {
int left=0, right=0, i , j, tmp=0, sum=0, close_tmp=INT_MAX, sum_tmp=0;
if (numsSize < 3) return NULL;
for (i=0;i<numsSize;i++){ // 排序
for (j=i+1;j<numsSize;j++){
if (nums[i]>nums[j]) {
tmp=nums[i];
nums[i]=nums[j];
nums[j]=tmp;
}
}
}
for(i = 0; i < numsSize - 2; i++){
left = i + 1;
right = numsSize - 1;
while(left < right){
sum = nums[i] + nums[left] + nums[right];
// 如果三個數的和大於等於目標數,那將尾指針向左移
if(sum > target) {
if (sum-target < close_tmp ) {
close_tmp = sum-target;
sum_tmp = sum;
}
right--;
// 如果三個數的和小於目標數,那將頭指針向右移
} else {
if (sum < target) {
if (target - sum < close_tmp) {
close_tmp = target - sum;
sum_tmp = sum;
}
left++;
} else {
return sum;
}
}
}
}
return sum_tmp;
}