Thursday, June 12, 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). 

Solution:

public class Solution {
    public int threeSumClosest(int[] num, int target) {
        Arrays.sort(num);
        int closest = 0;
        int error = Integer.MAX_VALUE;
        for(int i =0; i< num.length-2; i++)
        {
            int begin = i+1;
            int end = num.length-1;
            while(begin<end)
            {
                if( Math.abs(num[i]+num[begin]+num[end]-target)<error)
                {
                    error = Math.abs(num[i]+num[begin]+num[end]-target);
                    closest = num[i]+num[begin]+num[end];
                }
                if(num[i]+num[begin]+num[end]>target)
                    end--;
                else
                    begin++;
            }
        }
        return closest;
    }
}

No comments :

Post a Comment