其他分享
首页 > 其他分享> > 16. 3Sum Closest (M)

16. 3Sum Closest (M)

作者:互联网

3Sum Closest (M)

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

题意

求一三元对,使其和最接近给定的值。

思路

15. 3Sum 类似,只是修改了判定的标准。先排序,后利用two pointers并去除重复值即可。


代码实现

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int min = Integer.MAX_VALUE;
        int ans = 0;
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            // 去除重复的i
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int j = i + 1, k = nums.length - 1;
            while (j < k) {
                int sum = nums[i] + nums[j] + nums[k];
                int diff = Math.abs(sum - target);
                if (diff < min) {
                    min = diff;
                    ans = sum;
                }
                // 移动j、k的标准是使sum更加接近target
                if (sum < target) {
                    j++;
                    while (j < k && nums[j] == nums[j - 1]) {
                        j++;
                    }
                } else if (sum > target) {
                    k--;
                    while (j < k && nums[k] == nums[k + 1]) {
                        k--;
                    }
                } else {
                    return sum;		// 特殊情况,sum正好为target
                }
            }
        }
        return ans;
    }
}

标签:target,Closest,nums,3Sum,sum,16,int,while,ans
来源: https://blog.csdn.net/mapoos/article/details/98235234