threeSumClosest

16. 最接近的三数之和
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。
找出 nums 中的三个整数,使得它们的和与 target 最接近。
返回这三个数的和。假定每组输入只存在唯一答案。

示例:

输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
 

提示:
3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4
public class threeSumClosest {
    public int threeSumClosest(int[] nums, int target) {
        int len = nums.length;
        Arrays.sort(nums);
        int ans = nums[0] + nums[1] + nums[2];
        for(int i=0; i<len; i++){
            int l = i+1;
            int r = len-1;
            while(l<r){
                int res = nums[i] + nums[l] + nums[r];
                if(Math.abs(target-res) < Math.abs(target-ans)){
                    ans = res;
                }
                if(res > target){
                    r--;
                    while(l<r && nums[r]== nums[r+1]) r--;
                }else if(res < target){
                    l++;
                    while(l<r && nums[l]== nums[l-1]) l++;
                }else{
                    return target;
                }
            }
        }
        return ans;
    }
}
原文地址:https://www.cnblogs.com/athony/p/13159281.html