3 Sum Closest

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.

    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Solution:

public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        if(nums.length<3) return 0;
        int closestSum = nums[0]+nums[1]+nums[2];
        Arrays.sort(nums);
        for(int i=0; i<nums.length-2; i++){
            if(i!=0 && nums[i]==nums[i-1]) continue;
            int l=i+1, r=nums.length-1;
            while(l<r){
                int sum = nums[i]+nums[l]+nums[r];
                if(Math.abs(closestSum-target)>Math.abs(sum-target)) closestSum = sum;
                if(sum<target){
                    l++;
                } else if(sum>target){
                    r--;
                } else {
                    return target;
                }
            }
        }
        return closestSum;
    }
}
comments powered by Disqus