3Sum Closest

public int threeSumClosest(int[] num, int target) {

        //int d = 0;

        if(num==null || num.length<3) return 0;

        int d = target - num[0]-num[1]-num[2];

        int d_min = d;

        //老忘记排序!

        Arrays.sort(num);

        

        for(int i=0; i<num.length-2; i++){

            int low = i+1, high=num.length-1;

            while(low<high){

                d = target-(num[i]+num[low]+num[high]);

                if(d==0) return target;

                if(d<0) high--;

                if(d>0) low++;

                

                if(Math.abs(d)<Math.abs(d_min))

                    d_min = d;

            }

        }

        return target-d_min;

    }

 

你可能感兴趣的:(close)