LeetCode *** 16. 3Sum Closest

来源:互联网 发布:python sample 编辑:程序博客网 时间:2024/05/01 05:43

题目:

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


分析:

看此题标签即可。。


代码:

class Solution {public:    int threeSumClosest(vector<int>& nums, int target) {        int size=nums.size();        if(size<4){            if(size==0)return 0;            if(size==1)return nums[0];            if(size==2)return nums[0]+nums[1];            if(size==3)return nums[0]+nums[1]+nums[2];        }                int res=target>=0?INT_MAX:INT_MIN;        sort(nums.begin(),nums.end());                for(int i=0;i<size-2;++i){            int j=i+1,k=size-1,tmp=target>=0?INT_MAX:INT_MIN;;                        while(j<k){                if(abs(nums[i]+nums[j]+nums[k]-target)<abs(tmp-target))                    tmp=nums[i]+nums[j]+nums[k];                if(nums[i]+nums[j]+nums[k]>target)k--;                else if(nums[i]+nums[j]+nums[k]<target)j++;                else break;            }                        if(abs(tmp-target)<abs(res-target))                res=tmp;            if(res==target)break;                    }        return res;             }};

0 0
原创粉丝点击