Given an array nums of n integers and an integer target, find three
integers in nums such that the sum is closest to target. Return the
sum of the three integers. You may assume that each input would have
exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
感觉与上一题类似,可以使用双指针避免无用的判断

public int threeSumClosest(int[] nums, int target) {
    if(nums==null || nums.length<3) return 0;
    Arrays.sort(nums);
    int ret=nums[0]+nums[1]+nums[2];
    for(int i=0;i<nums.length-2;i++){
        if(i>0 && nums[i]==nums[i-1]) continue;
        int left=i+1;
        int right=nums.length-1;
        while(right>left){
            if(left>i+1 && nums[left]==nums[left-1]){
                left++;
                continue;
            }
            if(right<nums.length-1 && nums[right]==nums[right+1]){
                right--;
                continue;
            }
            int sum=nums[i]+nums[left]+nums[right];
            int diff=sum-target;
            if(diff==0) return sum;
            else{
                if(Math.abs(diff)<Math.abs(ret-target)) ret=sum;
                if(diff<0) left++;
                else right--;
            }
        }
    }
    return ret;
}

程浩
21 声望2 粉丝