Friday, February 7, 2014

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:
Typical N-Sum question.
1. Sort the array.
2. Iterate the sorted array, for each element a, use two pointers b and c. b starts from a+1, goes from left to right. c starts at the end, goes from right to left. 
If a+b+c > target, c--;
If a+b+c < target, b++; 
Thus, for each element, we only need O(n). Overall time complexity can be reduced to O(n^2).
public class Solution {
    public static int threeSumClosest(int[] num, int target) {
        if(num.length <= 2) return 0;
        Arrays.sort(num);
        int left = 0;
        int right = 0;
        int diff = 0;
        int sum = 0;
        int minSum = num[0] + num[1] + num[2];
        int minDiff = Integer.MAX_VALUE;
        for(int i = 0; i <= num.length - 3; i++){
            left = i + 1;
            right = num.length - 1;
            while(left < right){
                sum = num[i] + num[left] + num[right];
                diff = sum - target;
                if(diff > 0) right--;
                if(diff < 0) left++;
                if(diff == 0) return sum;
                if(Math.abs(diff) < minDiff){
                    minDiff = Math.abs(diff);
                    minSum = sum;
                }
            }
        }
        return minSum;
    }
}

No comments:

Post a Comment