16. 3Sum Closest

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int ret=nums[0]+nums[1]+nums[2];
        for(int i=0;i<nums.length;i++)
        {
            int l=i+1;
            int r=nums.length-1;
            while(l<r)
            {
                int sum=nums[i]+nums[l]+nums[r];
                if(sum==target)
                    return target;
                if(Math.abs(sum-target)<Math.abs(ret-target))
                    ret=sum;
                if(sum-target<0)
                    l++;
                else
                    r--;
            }
        }
        return ret;
    }
}

 

posted @ 2017-09-22 12:55  Weiyu Wang  阅读(116)  评论(0编辑  收藏  举报