LeetCode | 16. 3Sum Closest

来源:互联网 发布:铭兴茶业淘宝网 编辑:程序博客网 时间:2024/06/03 20:13

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

提供三种思路.

第一种,朴素的O(n^3)加一点优化,106ms擦边AC,(击败1.56%的人23333)

class Solution {public:        int threeSumClosest(vector<int>& nums, int target)        {            int res = 0;            int delta = 999999;            int len = nums.size();            sort(nums.begin(),nums.end());            for(int i=0;i<len;i++)            {                for(int j=i+1;j<len;j++)                {                    int tsum = nums[i]+nums[j];                    for(int k=j+1;k<len;k++)                    {                        if(abs(tsum+nums[k]-target) < delta)                        {                            delta = abs(nums[i]+nums[j]+nums[k]-target);                            res = nums[i]+nums[j]+nums[k];                        }                        if(tsum+nums[k] > target)                        {                            break;                        }                    }                }            }            return res;        }};







第二种,类似3SUM问题,对于某一确定的值T,利用O(N^2)算法判断nums中是否存在三个数和为T.如果存在,返回T.这个T,是从给定的Target开始,左右浮动,设它上限为10000,复杂度为O(c * N^2),9ms AC,排名基本上在前10%了

class Solution {public:        bool find(vector<int>& v, int sum)//判断是否存在和为sum的三个数 O(n^2)        {            int len = v.size();            for(int i=0;i<len;i++)            {                int left = i+1, right = len-1;                while(left < right)                {                    if(v[left]+v[right] == sum-v[i])                    {                        return true;                    }                    else if(v[left]+v[right] < sum-v[i])                    {                        left++;                    }                    else                    {                        right--;                    }                }                while(v[i]==v[i+1])                {                    i++;                }            }            return false;        }        int threeSumClosest(vector<int>& nums, int target)        {            int res = 0;            sort(nums.begin(),nums.end());            for(int i=0;i<10000;i++)            {                if(find(nums,target+i))                {                    return target+i;                }                if(find(nums,target-i))                {                    return target-i;                }            }            return res;        }};







第三种,参考大神们提供的思路,类似3Sum的两个指针.

----------------------------------------------------^  ^                                               ^|  |                                               ||  +- second                                     third+-first

if nums[first] + nums[second] + nums[third] is smaller than the target, we know we have to increase the sum. so only choice is moving the second index forward.

----------------------------------------------------^    ^                                             ^|    |                                             ||    +- second                                   third+-first

if the sum is bigger than the target, we know that we need to reduce the sum. so only choice is moving ‘third’ to backward. of course if the sum equals to target, we can immediately return the sum.

----------------------------------------------------^    ^                                          ^|    |                                          ||    +- second                                third+-first

when second and third cross, the round is done so start next round by moving ‘first’ and resetting second and third.

----------------------------------------------------  ^    ^                                           ^  |    |                                           |  |    +- second                                 third  +-first

while doing this, collect the closest sum of each stage by calculating and comparing delta. Compare abs(target-newSum) and abs(target-closest). At the end of the process the three indexes will eventually be gathered at the end of the array.

----------------------------------------------------                                         ^    ^    ^                                         |    |    `- third                                         |    +- second                                         +-first

if no exactly matching sum has been found so far, the value in closest will be the answer.

class Solution {public:        int threeSumClosest(vector<int>& nums, int target)        {            int len = nums.size();            int delta = 99999;            int res = 0;            sort(nums.begin(),nums.end());            for(int i=0;i<len;i++)            {                int left = i+1, right = len-1;                while(left < right)                {                    int tsum = nums[left]+nums[right]+nums[i];                    if(abs(target-tsum) < delta)                    {                        delta = abs(target-tsum);                        res = tsum;                    }                    if(tsum == target)                    {                        return target;                    }                    else if(tsum < target)//移动左边的指针                    {                        left++;                    }                    else                    {                        right--;                    }                }            }            return res;        }};
1 0