3sum closest to target

给一个包含n个整数的数组S, 找到和与给定整数target最接近的三元组,返回这三个数的和。

class Solution {
public:    
    /**
     * @param numbers: Give an array numbers of n integer
     * @param target: An integer
     * @return: return the sum of the three integers, the sum closest target.
     */
    int threeSumClosest(vector<int> nums, int target) {
        // write your code here
        int n=nums.size();
        //if(n<3) return 0;
        //if(n==3) return nums[0]+nums[1]+nums[2];
        sort(nums.begin(),nums.end());
        int res=nums[0]+nums[1]+nums[2];
        for(int i=0;i<n-2;i++){
            int left=i+1;
            int right=n-1;
            while(left<right){
                int sum3=nums[i]+nums[left]+nums[right];
                if(sum3<target){
                    if(abs(sum3-target)<abs(res-target)){
                        res=sum3;
                    }
                    left++;

                }else if(sum3>target){
                    if(abs(sum3-target)<abs(res-target)){
                        res=sum3;
                    }
                    right--;                  
                }else{
                    return target;
                }
            }
        }
        return res;
    }
};


你可能感兴趣的:(3sum closest to target)