# 14. 最接近的三数之和

java

```java
import java.util.Arrays;

/**
 *
 * 16. 最接近的三数之和
 *
 * 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数，使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
 *
 * 例如，给定数组 nums = [-1，2，1，-4], 和 target = 1.
 *
 * 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
 */
public class Solution16 {

    /**
     * 双指针，类似 Solution15
     * 不需要去重
     *
     * @param nums
     * @param target
     * @return
     */
    public int threeSumClosest(int[] nums, int target) {
            Arrays.sort(nums);
            int minDistance=Integer.MAX_VALUE;//最小距离
            int minSum=0;//最小和
            for(int i=0;i<nums.length-2;i++){
                int k=i+1;//前指针
                int v=nums.length-1;//后指针
                while(k<v){
                    int sum=nums[i]+nums[k]+nums[v];
                    if(sum==target) return sum;
                    else if(sum>target){
                        v--;
                    }else{
                        k++;
                    }
                    //保存最小和、最小距离
                    if(Math.abs(sum-target)<minDistance){
                        minDistance=Math.abs(sum-target);
                        minSum=sum;
                    }
                }
            }
            return minSum;
    }
    public static void main(String[] args){
        int[] nums={
                -1,2,1,-4
        };
        int target=1;
        int r=new Solution16().threeSumClosest(nums,target);
        System.out.println(r);//output:2
    }
}
```

python

```python
class Solution:
    '''
    找到数组中结果与k接近的3个元素
    '''

    def threeSumClosest(self, numbers, target):
        # 排序
        numbers.sort()
        # 最接近的和
        ans = None
        # 结果列表
        res = []
        for i in range(len(numbers)):
            left, right = i + 1, len(numbers) - 1
            # 从i号位置开始搜索，i=0时搜索右边所有的，i=3时，不搜索0,1,2，因为0-3,1-3,2-3的组合前面已经搜索过了
            while left < right:
                sum = numbers[left] + numbers[i] + numbers[right]
                # 比较最近和
                if ans is None or abs(sum - target) < abs(ans - target):
                    ans = sum
                    res = [numbers[i], numbers[left], numbers[right]]
                # 因为已经从小到大排序
                if sum <= target:  # 小于target时尝试左边变得更大
                    left += 1
                else:  # 大于target时尝试右边变得更小
                    right -= 1
        return ans, res


s = Solution()
print(s.threeSumClosest([-1, 1, 2, -4, -1], 1))
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://im-qianuxn.gitbook.io/pytorch/ji-suan-ji/shua-ti/zhi-shang-lei/14-zui-jin-san-shu-zhi-he.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
