#16 3Sum Closest

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.