16.3Sum Closest

给定一个数组和一个目标数,求数组中的任意三个元素之和,与目标数最接近,返回和值。


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 十分类似,所以解题思路也沿用,只是将 3Sum = 0,变成 abs(3Sum - target)最小值即可。值得注意的是,对 res 的初始值给定,因为结果是从大到小慢慢收敛的,所以 res 需要给一个比较大的数,而如果 res = INT_MAX ,则减去负数会溢出;给小了不能收敛到答案,所以,将 res 赋予数组中最大的三个数之和。

int threeSumClosest(vector<int>& nums, int target) {
    sort(nums.begin(), nums.end());
    int nums_length = nums.size(), res = nums[nums_length - 1] + nums[nums_length - 2] + nums[nums_length - 3];
    for (int i = 0; i < nums_length-2; i++) {
        int l = i + 1, r = nums_length - 1, remain = target - nums[i];
        while (l < r) {
            int sum = nums[l] + nums[r];
            res = abs(sum - remain) < abs(res-target) ? sum + nums[i] : res;
            if (sum > remain) r--;
            else if (sum <= remain) l++;
        }
    }
    return res;
}

猜你喜欢

转载自www.cnblogs.com/luo-c/p/12911172.html