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的解题,先排序,每次固定下第i个位置的元素,然后在第i个位置后的元素中利用左右指针找到当中距离target距离最小的包含第i个元素的三元素组合。再从这些局部最佳的组合中,找到最佳的那个。
以下是AC的代码
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int left, right;
int bestSum;
int leastDis = INT_MAX;
sort(nums.begin(),nums.end());
for (int i = 0; i < nums.size()-1; i++) {
left = i+1;
right = nums.size()-1;
while (left < right) {
int sum = nums[i]+nums[left]+nums[right];
int dis = sum-target;
if (abs(dis) < leastDis) {
bestSum = sum;
leastDis = abs(dis);
}
if (sum < target) {
while (left<right && nums[left]==nums[left+1]) left++;
left++;
} else if (sum > target) {
while (left<right&& nums[right] == nums[right-1]) right--;
right--;
} else {
return target;
}
}
}
return bestSum;
}
};