#16 3Sum Closest

来源:互联网 发布:2016access数据库教程 编辑:程序博客网 时间:2024/05/18 01:42

题目链接:https://leetcode.com/problems/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).


void Sort(int *data,int n) {<span style="white-space:pre"></span>//归并排序非递归实现int *tmp = (int *)malloc(n * sizeof(int));int lBegin, lEnd, rBegin, rEnd;int i,j,k;int len = 1;while (len < n) {lBegin = 0;lEnd = len - 1;rBegin = len;while (rBegin < n) {rEnd = lEnd + len < n - 1 ? lEnd + len : n - 1;i = lBegin,j = rBegin,k = lBegin;while (i <= lEnd && 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);       //先排序    for(i = 0; i < numsSize; ++i) {     //每趟一个数固定,另两个数分别从剩下数列的第一个和最后一个中间逼近        j = i + 1;        k = numsSize - 1;        while(j < k) {            sum = nums[i] + nums[j] + nums[k];            if(sum < target) {          //和小于target,只有增大j才能使sum变大,从而更接近target                if(abs(sum-target) < abs(closestSum-target))        //如果更接近target更新closetSum                    closestSum = sum;                ++j;            }            else if(sum > target) {     //和大于target,减小sum                if(abs(sum-target) < abs(closestSum-target))                    closestSum = sum;                --k;            }             else            //如果等于target是接近答案,直接返回结果                return sum;        }    }    return closestSum;}


0 0