Wednesday, February 25, 2015

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:
This problem is similar with 3 Sum. This kind of problem can be solve by using similar approach, i.e., two pointers from both left and right.
总的时间复杂度为O(n^2+nlogn)=(n^2),空间复杂度是O(n)
public class Solution {
    public int threeSumClosest(int[] num, int target) {
        int min = Integer.MAX_VALUE;
        int res = 0;
        int diff = 0;
        Arrays.sort(num);

        for(int i = 0; i < num.length; i++) {
            int j = i + 1;
            int k = num.length - 1;
            while(j < k) {
                int sum = num[i] + num[j] + num[k];
                diff = Math.abs(target - sum);

                if(diff < min) {
                    min = diff;
                    res = sum;
                }
                
                if(sum <= target)
                    j++;
                else
                    k--;
            }
        }
        return res;
    }
}

No comments:

Post a Comment