> For the complete documentation index, see [llms.txt](https://junnie.gitbook.io/nine-chapter/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://junnie.gitbook.io/nine-chapter/7.two-pointers/533two-sum-closest-to-target.md).

# 533.Two Sum - Closest to target

## 1.Description(Medium)

Given an array`nums`of*n\_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 array`nums`=`[-1, 2, 1, -4]`, and*target*=`4`.

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

[**Challenge**](https://www.lintcode.com/en/problem/two-sum-closest-to-target/#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;
    }
```
