533.Two Sum - Closest to target

1.Description(Medium)

Given an arraynumsofn_integers, find two integers in_nums_such that the sum is closest to a given number,_target.

Return the difference between the sum of the two integers and the target.

Example

Given arraynums=[-1, 2, 1, -4], andtarget=4.

The minimum difference is1. (4 - (2 + 1) = 1).

Challenge

Do it in O(nlogn) time complexity.

2.Code

用一个mindiff来记录最小值

 public int twoSumClosest(int[] nums, int target) {
        if(nums==null || nums.length<2){
            return -1;
        }
        Arrays.sort(nums);
        int mindiff=Integer.MAX_VALUE;
        int head=0;
        int tail=nums.length-1;
        while(head<tail){
            int sum=nums[head]+nums[tail];
            if(sum==target){
                return 0;
            }
            else if(sum>target){
                tail--;
            }else{
                head++;
            }
            int diff=Math.abs(sum-target);
            if(diff<mindiff){
                mindiff=diff;
            }
        }
        return mindiff;
    }

Last updated