16. 3Sum 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).
int threeSumClosest(int* nums, int numsSize, int target) { int inner_target; int i = 0, j, k; int *solutionSet; //element in the returnArray int** returnArray = NULL; int diff; int min_diff = INT_MAX; int ret; quickSort(nums, 0, numsSize-1); for(; i < numsSize-2; i++){ //最外层遍历每个元素 inner_target = target-nums[i]; //里层: Two Sum j = i+1; k = numsSize-1; while(j<k){ diff = abs(inner_target-nums[j]-nums[k]); if(diff < min_diff) { min_diff = diff; ret = nums[i]+nums[j]+nums[k]; } if(nums[j]+nums[k] < inner_target) j++; else if(nums[j]+nums[k] > inner_target) k--; else return target; } } return ret; } void quickSort(int* nums, int start, int end){ int p1 = start+1; int p2 = end; int tmp; while(p1 <= p2){ while(p1 <= p2 && nums[p1] <= nums[start]){ p1++; } while(p1 <= p2 && nums[p2] > nums[start]){ p2--; } if(p1 < p2){ tmp = nums[p1]; nums[p1] = nums[p2]; nums[p2] = tmp; p1++; p2--; } } //put the sentinel at the end of the first subarray if(start!=p2){ tmp = nums[start]; nums[start] = nums[p2]; nums[p2] = tmp; } if(start < p2-1) quickSort(nums,start, p2-1); //sort first subarray (<=sentinel) if(p1 < end) quickSort(nums,p1, end); //sort second subarray (>sentinel) }