16. 3Sum Closest

来源:互联网 发布:http 前端展示数据库 编辑:程序博客网 时间:2024/06/06 05:35

题目: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).


和3Sum  的和为0 的,最大的区别就是,在3sum中,当三个数为0时候,begin后面的数begin位置的数相等时候,和end位置和end前面的位置相等时,不需要进行++和---。

//while(b<e && nums[b]==nums[b+1] )b++;
//while(b<e && nums[e]==nums[e-1] )e--;

即上面这两句话不要。


代码:

void sort(int *a, int left, int right);int threeSumClosest(int* nums, int numsSize, int target) {    printf("The size is %d, the target is %d\n",numsSize,target);        int sub=0;    int ret=nums[0]+nums[1]+nums[2];    int closest=abs(ret-target);        sort(nums,0,numsSize-1);        for(int i=0;i<numsSize-2;i++)    {        int b=i+1;        int e=numsSize-1;                if(i>0 && nums[i]==nums[i-1])continue;        while(b<e)        {            int sum=nums[i]+nums[b]+nums[e];                        if(sum==target)            {                return sum;            }            else            {                             int tmp=abs(target-sum);                if(tmp < abs(closest))                {                    closest=tmp;                    ret=sum;                }                                //while(b<e && nums[b]==nums[b+1] )b++;                //while(b<e && nums[e]==nums[e-1] )e--;                                if(sum < target)                {                    b++;                }                else if(sum > target)                {                    e--;                }            }        }    }        return ret;    }void sort(int *a, int left, int right){if(left >= right){return ;}int i = left;int j = right;int key = a[left];while(i < j)                              {while(i < j && key<a[j]){j--;}        if(i<j)    a[i++] = a[j];while(i < j && key >a[i]){i++;}        if(i<j)    a[j--]= a[i];}a[i] = key;sort(a, left, i - 1);sort(a, i + 1, right);} 

















0 0
原创粉丝点击