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; }
Java 版:
class Solution { public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int res = nums[0] + nums[1] + nums[2]; for(int i = 0; i < nums.length; i++){ if(i > 0 && nums[i] == nums[i-1]) continue; int L = i + 1, R = nums.length - 1, sum = 0; while(L < R){ sum = nums[i] + nums[L] + nums[R]; if(Math.abs(res - target) > Math.abs(sum - target)) res = sum; if(sum > target) R--; else if(sum < target) L++; else return target; } } return res; } }