【Leetcode】16. 最接近的三数之和

295 阅读1分钟

题目描述

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

题解

解法和【Leetcode】15. 三数之和很像的,只是我们不再需要看等于0的条件了,而是尽可能地接近目标数target,并且依据和target的差值,来更新最接近的和。

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int res = nums[0] + nums[1] + nums[nums.length - 1];
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                if (Math.abs(nums[i] + nums[left] + nums[right] - target) < Math.abs(res - target)) {
                    res = nums[i] + nums[left] + nums[right];
                }
                if (nums[i] + nums[left] + nums[right] < target) {
                    left++;
                }
                else if (nums[i] + nums[left] + nums[right] > target) {
                    right--;
                }
                else {
                    return target;
                }
            }
        }
        return res;
    }
}