Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
解法:与3Sum问题一样,可以通过先确定一个数再转化为2Sum问题,只不过此时两个数之和不是等于target,而是三个数之和最接近target,即2Sum问题的两个数之和最接近target-nums[i](i=0,1,...,n-1)。
class Solution { public: int threeSumClosest(vector<int>& nums, int target) { int n = nums.size(); int closest = 0; int diff = INT_MAX; sort(nums.begin(), nums.end()); for(int i = 0; i < n - 2; i++) { int left = i + 1, right = n - 1; int tar = target - nums[i]; while(left < right) { int tmp = nums[left] + nums[right]; int dist = abs(tar - tmp); if(dist < diff) { diff = dist; closest = nums[i] + nums[left] + nums[right]; } if(nums[i] + nums[left] + nums[right] < target) left++; else right--; } } return closest; } };
class Solution { public: int threeSumClosest(vector<int>& nums, int target) { int n = nums.size(); int closest = nums[0] + nums[1] + nums[2]; int diff = abs(closest - target); sort(nums.begin(), nums.end()); for(int i = 0; i < n - 2; i++) { int left = i + 1, right = n - 1; while(left < right) { int sum = nums[i] + nums[left] + nums[right]; int dist = abs(sum - target); if(dist < diff) { diff = dist; closest = sum; } if(sum < target) left++; else right--; } } return closest; } };