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

详见:https://leetcode.com/problems/3sum-closest/description/

实现语言:Java

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int size=nums.length;
        if(size<3||nums==null){
            return 0;
        }
        int closest=nums[0]+nums[1]+nums[2];
        int diff=Math.abs(closest-target);
        Arrays.sort(nums);
        for(int i=0;i<size-2;++i){
            int j=i+1;
            int k=size-1;
            while(j<k){
                int sum=nums[i]+nums[j]+nums[k];
                int newDiff=Math.abs(sum-target);
                if(diff>newDiff){
                    diff=newDiff;
                    closest=sum;
                }
                if(sum>target){
                    --k;
                }else{
                    ++j;
                }
            }
        }
        return closest;
    }
}

 实现语言:C++

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int size=nums.size();
        if(nums.empty()||size<3)
        {
            return 0;
        }
        int closest=nums[0]+nums[1]+nums[2];
        int diff=abs(closest-target);
        sort(nums.begin(),nums.end());
        for(int i=0;i<size-2;++i)
        {
            int j=i+1;
            int k=size-1;
            while(j<k)
            {
                int sum=nums[i]+nums[j]+nums[k];
                int newDiff=abs(sum-target);
                if(diff>newDiff)
                {
                    diff=newDiff;
                    closest=sum;
                }
                if(sum>target)
                {
                    --k;
                }
                else
                {
                    ++j;
                }
            }
        }
        return closest;
    }
};
原文地址:https://www.cnblogs.com/xidian2014/p/8546260.html