Leetcode 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).

解析

找出一个数组中的三个数,总和最接近目标值。
根据上题寻找三个数使其和为0的逻辑可知,先将数组排序,然后依次选定一个值,之后逐步向目标值靠拢,如果找到绝对值接近目标值的,保存当前结果。最后输出最接近的总和。如果找到正好相等的,可以直接返回结果。

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])
        /*而寻找结束的条件就是,1,找到一个小于或者大于key的数(大于或小于取决于你想升
        序还是降序)2,没有符合条件1的,并且i与j的大小没有反转*/ 
        {
            j--;/*向前寻找*/
        }
         
        a[i] = a[j];
        /*找到一个这样的数后就把它赋给前面的被拿走的i的值(如果第一次循环且key是
        a[left],那么就是给key)*/
         
        while(i < j && key >= a[i])
        /*这是i在当组内向前寻找,同上,不过注意与key的大小关系停止循环和上面相反,
        因为排序思想是把数往两边扔,所以左右两边的数大小与key的关系相反*/
        {
            i++;
        }
         
        a[j] = a[i];
    }
     
    a[i] = key;/*当在当组内找完一遍以后就把中间数key回归*/
    sort(a, left, i - 1);/*最后用同样的方式对分出来的左边的小组进行同上的做法*/
    sort(a, i + 1, right);/*用同样的方式对分出来的右边的小组进行同上的做法*/
                       /*当然最后可能会出现很多分左右,直到每一组的i = j 为止*/
}
int absoluteValue(int a,int b)
{
    if(a>b)return a-b;
    else return b-a;
}
int threeSumClosest(int* nums, int numsSize, int target) {
    int i=0,j=0,k=0,ans=nums[0]+nums[1]+nums[2];
    sort(nums,0,numsSize-1);
    for(i=0;iabsoluteValue(nums[i]+nums[j]+nums[k],target))
                    ans=nums[i]+nums[j]+nums[k];
                j++;
            }
            else
            {
                if(absoluteValue(ans,target)>absoluteValue(nums[i]+nums[j]+nums[k],target))
                    ans=nums[i]+nums[j]+nums[k];
                k--;
            }
            //printf("%d %d\n",i,ans);
        }
    }
    return ans;
}

你可能感兴趣的:(Leetcode 16. 3Sum Closest)