16. 最接近的三数之和

题干

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

例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.

与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum-closest

思路

这个和15. 三数之和思想一样。

完整代码

class Solution {
	public static int threeSumClosest(int[] nums, int target) {
        int result = nums[0] + nums[1] + nums[2];
        Arrays.sort(nums);

        for (int start = 0; start < nums.length - 2; start++) {
            int j = start + 1, end = nums.length - 1;

            while (j < end) {
                int tmpSum = nums[start] + nums[j] + nums[end];
                if (Math.abs(tmpSum - target) < Math.abs(result - target)) {
                    result = tmpSum;
                }
                if (tmpSum < target) {
                    j++;
                } else if (tmpSum > target) {
                    end--;
                } else {
                    return result;
                }
            }
        }
        return result;
    }
}

更好的代码

多加几个判断条件节省时间。

class Solution {
	public int threeSumClosestBest(int[] nums, int target) {
        Arrays.sort(nums);
        int result = Integer.MAX_VALUE, left, right, min = Integer.MAX_VALUE;
        for (int k = 0; k < nums.length - 2; k++) {
            left = k + 1;
            right = nums.length - 1;

            // 区间[left,right]内,和最小的值
            int rangeMin = nums[k] + nums[left] + nums[left + 1];
            // 区间[left,right]内,和最大的值
            int rangeMax = nums[k] + nums[right] + nums[right - 1];
            if (rangeMin > target) {
                // 区间最小值比目标大, 没必要寻找区间其他值的和了
                if (rangeMin - target < min) {
                    min = rangeMin - target;
                    result = rangeMin;
                }
            } else if (rangeMax < target) {
                // 区间最大的值比目标还要小,也没必要寻找区间其他值的和了
                if (target - rangeMax < min) {
                    min = target - rangeMax;
                    result = rangeMax;
                }
            } else {
                while (left < right) {
                    int sum = nums[left] + nums[right] + nums[k];
                    if (sum < target) {
                        left++;
                    } else if (sum > target) {
                        right--;
                    } else {
                        return sum;
                    }
                    if (Math.abs(sum - target) < min) {
                        result = sum;
                        min = Math.abs(sum - target);
                    }
                }
            }
        }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值