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).
public int threeSumClosest(int[] nums, int target) {
        int length = nums.length;
        Arrays.sort(nums);
        int diff=Integer.MAX_VALUE;
        int sumclosest=Integer.MAX_VALUE;
        for (int i = 0; i < length-2; i++) {
            if(i>0&&nums[i]==nums[i-1]){
                continue;
            }
            int head = i+1;
            int tail = length-1;
            while (head<tail){
                int tmp = nums[i]+nums[head]+nums[tail];
                int newdiff = Math.abs(tmp-target);
                if (diff>newdiff){
                    diff = newdiff;
                    sumclosest = tmp;
                }
                if (tmp<target){
                    head++;
                }
                else if (tmp>target){
                    tail--;
                }
                else {
                    int k=head+1;
                    while (k<tail&&nums[k]==nums[k-1]){
                        k++;
                    }
                    head = k;
                    int l=tail-1;
                    while (l>head&&nums[l]==nums[l+1]){
                        l--;
                    }
                    tail = l;
                }
            }
        }
        return sumclosest;
    }
posted @ 2017-11-21 14:50  binryang  阅读(79)  评论(0编辑  收藏  举报