Title Link: https://leetcode.com/problems/3sum-closest/
Given an array S of n integers, find three integers in S such so the sum is closest to a give n number, target. Return the sum of the three integers. You may assume this each input would has exactly one solution.
For example, given array S = {-1 2 1-4}, and target = 1. The sum is closest to the target is 2. (-1 + 2 + 1 = 2).
void sort (int *data,int n) {<span style= "white-space:pre" ></span>//merge sort non-recursive implementation int *tmp = (int *) malloc (n * Size of (int)); int Lbegin, lEnd, Rbegin, rend;int i,j,k;int len = 1;while (len < n) {lbegin = 0;lend = Len-1;rbegin = Len;w Hile (Rbegin < n) {rEnd = lEnd + Len < n-1? lEnd + len:n-1;i = Lbegin,j = Rbegin,k = Lbegin;while (i <= LE nd && J <= rEnd) {if (Data[i] <= data[j]) tmp[k++] = data[i++];elsetmp[k++] = data[j++];} while (i <= lEnd) tmp[k++] = Data[i++];while (J <= rEnd) tmp[k++] = data[j++];for (i = lbegin; I <= rEnd; ++i) data[ I] = Tmp[i];lbegin + = 2 * Len;lend + = 2 * len;rbegin + 2 * len;} Len *= 2;} Free (TMP);} int Threesumclosest (int* nums, int numssize, int target) {int I, j, K; int sum, closestsum = nums[0] + nums[1] + nums[2]; Sort (Nums, numssize); Sort for (i = 0; i < numssize; ++i) {//one number per trip, and the other two for j = i + 1, respectively, from the first and last middle of the remaining series; K = numsSize-1; while (J < k) {sum = Nums[i] + nums[j] + nums[k]; if (sum < target) {//and less than target, only increase J to make the sum larger, thus closer to the target if (ABS (Sum-target) < ABS (closestsum -target))//If closer to target update closetsum closestsum = sum; ++j; } else if (Sum > Target) {//and greater than target, reduce sum if (ABS (Sum-target) < ABS (closestsum-target )) closestsum = sum; --k; } else//If the equals target is close to the answer, return the result directly to sum; }} return closestsum;}
#16 3Sum Closest