@@ -0,0 +1,1722 @@
+package com.fulin.Array;%0A%0Aimport java.util.Arrays;%0A%0A/**%0A * 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.%0A * For example, given array S = %7B-1 2 1 -4%7D, and target = 1.%0A * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).%0A *%0A * Created by fulin on 17-8-11.%0A */%0Apublic class ThreeSumClosest %7B%0A%0A    public  static int threeSumClosest(int%5B%5D nums, int target) %7B%0A        if(nums == null %7C%7C nums.length %3C 3)%7B%0A            return 0;%0A        %7D%0A%0A        Arrays.sort(nums);%0A        int m = nums.length;%0A%0A        int min = nums%5B0%5D + nums%5B1%5D + nums%5B2%5D;%0A        int max = nums%5Bm-1%5D + nums%5Bm-2%5D + nums%5Bm-3%5D;%0A%0A        if(target %3E= max)%7B%0A            return max;%0A        %7D%0A        if(target %3C= min)%7B%0A            return min;%0A        %7D%0A        int result = Math.abs(target - min) %3E Math.abs(target - max) ? max : min;%0A        int diff = Math.min(Math.abs(target - min) , Math.abs(max - target));%0A        for(int i=0;i %3C nums.length ; i++)%7B%0A            int left = i + 1 ;%0A            int right = nums.length - 1;%0A%0A            while(left %3C right)%7B%0A                int sum = nums%5Bi%5D + nums%5Bleft%5D + nums%5Bright%5D;%0A                int newDiff = Math.abs(target - sum);%0A                if(newDiff == 0)%7B%0A                    return target;%0A                %7D%0A                if(diff %3E newDiff)%7B%0A                    diff = newDiff;%0A                    result = sum;%0A                %7D%0A%0A                if(sum %3E target)%7B%0A                    right --;%0A                %7Delse%7B%0A                    left ++;%0A                %7D%0A            %7D%0A        %7D%0A%0A        return result;%0A    %7D%0A%7D%0A

leetcode : 16. 3Sum Closest