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).
给出一个大小为n 的int型数组和一个整数target。假设a, b, c为数组中的三个元素,sum = a + b + c。求出和 target最接近的sum。
本题的求解方法和我之前的 3Sum 的求解方法一致。都是先对数组排好序,然后固定一个数,移动另外的两个数来求和。
只不过之前那道题要求sum的值为0。而这道题要求sum最接近target。用result保存最接近target的sum。
所以,当sum的值等于target时,直接返回target。
否则,当 abs(target - sum) 小于 abs(result - sum) 时,result = sum。大于时result则不变。
注意:result 不能初始化为0,否则会出现问题。直接初始化为数组前3个元素之和即可。
#include
class Solution {
public:
int threeSumClosest(vector& nums, int target) {
int result = 0;
if (nums.size() <= 3) {
for (int i = 0; i < nums.size(); i++) {
result += nums[i];
}
return result;
}
sort(nums.begin(), nums.end());
result = nums[0] + nums[1] + nums[2];
int i, j, k;
for (i = 0; i < nums.size() - 2; i++) {
for (j = i + 1, k = nums.size() - 1; j < k;) {
int temp = nums[i] + nums[j] + nums[k];
if (temp == target) {
return target;
} else if (temp < target) {
j++;
} else {
k--;
}
if (abs(temp - target) < abs(result - target)) result = temp;
}
}
return result;
}
};