Thursday, January 16, 2014

Leetcode: 3sum-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).
Our approach:

We just select the all the possible combinations of two elements and use a variation of binary search that looks for the closest element instead of the exact one.

public class Solution {
    public int threeSumClosest(int[] num, int target) 
    {
        int error = Integer.MAX_VALUE;
        int solution = 0;
        if(num.length<3)
            return solution;
        Arrays.sort(num);
        for(int i=0; i<num.length-2; i++)
        {
            for(int j=i+1; j<num.length-1;j++)
            {
                int temp = findSumClosest(num, target, num[i]+num[j], j+1) + num[i] + num[j];
                if(error>Math.abs(target-temp))
                {
                    solution = temp;
                    error = Math.abs(target-temp);
                }
            }
        }
        return solution;
    }
    
    private int findSumClosest(int[] num, int target, int tempSum, int start)
    {
        int goal = target-tempSum;
        int p1 = start;
        int p2 = num.length-1;
        while(p1<p2)
        {
            int middle = (p1+p2)/2;
            if(Math.abs(num[middle]-goal)>Math.abs(num[middle+1]-goal))
                p1=middle+1;
            else
                p2=middle;
        }
        return num[p1];
    }
}

No comments :

Post a Comment