1. 题目
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).
2. 思路
先排序,遍历第一位。然后去查找符合要求的后两位。
后两位从头尾开始,向中间移动。如果结果偏小就移动小端,如果偏大就移动大端。找到整个移动过程中的最符合需求的数。
证明:第二个数为起点的所有pair中,最合适的一定的走到过的。
3. 代码
耗时:13ms
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int cv = target;
int diff = numeric_limits<int>::max();
for (int i1 = 0; i1 < nums.size() - 2; i1++) {
int i2 = i1 + 1;
int i3 = nums.size() - 1;
while (i2 < i3) {
int sum = nums[i1] + nums[i2] + nums[i3];
int nd = abs(sum - target);
if (nd == 0) return target;
if (nd < diff) {
diff = nd;
cv = sum;
}
if (sum < target) {
i2++;
} else {
i3--;
}
}
}
return cv;
}
};