美文网首页
16. 3Sum Closest

16. 3Sum Closest

作者: larrymusk | 来源:发表于2017-12-03 17:14 被阅读0次

    先排序,然后左右夹逼,
    每次当sum-target < diff 用diff记录下最小距离

    static int intcmp(const void *a, const void *b)
    {
        return(*(int *)a - *(int *)b);
    }
    
    
    
    int threeSumClosest(int* nums, int numsSize, int target) {
        
        qsort(nums, numsSize, sizeof(nums[0]), intcmp);
    
        int res=0, sum=0, diff=2147483647, start, end;
        
        for(int i=0; i<=numsSize-3;i++)
        {
            if(i>0 && nums[i]==nums[i-1])
                continue;
            
            start = i+1;
            end = numsSize-1;
            
            while(start<end)
            {
                sum = nums[i] + nums[start] + nums[end];
                if(sum<target){
                    if(target-sum < diff)
                    {
                        diff = target-sum;
                        res = sum;
                    }    
                    start++;
                }
                else if(sum>target){
                    if(sum-target < diff)
                    {
                        diff = sum-target;
                        res = sum;
                    }    
                    end--; 
                }
                else
                    return sum;
            }    
            
        }    
        
        return res;
    }

    相关文章

      网友评论

          本文标题:16. 3Sum Closest

          本文链接:https://www.haomeiwen.com/subject/hyxzbxtx.html