Description
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).
Solution
本題和15. 3Sum不同蓝撇,不是求很多組結果果复,而是一個最和target接近的三數之和sum而已,結果唯一渤昌,同樣的步驟虽抄,做好中間結果的保存
int threeSumClosest(vector<int>& nums, int target) {
int closestSum = nums[0] + nums[1] + nums[2];
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size() - 2; ++i) {
if (target < 0 && nums[i] > 0) {//提前剪枝
break;
}
int begin = i + 1, end = nums.size() - 1;
while (begin < end) {
int sum = nums[i] + nums[begin] + nums[end];
if (abs(closestSum - target) > abs(sum - target)) { //如果出現(xiàn)更接近的sum
closestSum = sum;
}
if (sum > target) {
end--;
} else if (sum < target) {
begin++;
} else {
return target;
}
}
}
return closestSum;
}