LeetCode 16---3Sum Closest

题目链接:LeetCode 16—3Sum Closest

求一个无序数组中三个数的和最接近目标数的结果,
先排序再进行计算即可,实现代码如下:

public class Problem16 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }
    public static int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        if(nums.length<3) return -999;
        int sum=nums[0]+nums[1]+nums[2];
        for(int i=0;i<nums.length-2;i++){
            int j=i+1;
            int k=nums.length-1;
            while(j<k){
                int go=nums[i]+nums[j]+nums[k];
                if(go==target) return go;
                else if(go>target) k--;
                else j++;
                if(Math.abs(go-target)<Math.abs(sum-target)){
                    sum=go;     
                }

            }
        }
        return sum;

    }

}

你可能感兴趣的:(LeetCode,算法)