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).
如上例, -1 + 1 = 0 不也接近 1 吗?不行,因为人家要求3数之和.
思路同15题 3Sum. 既固定i
, 让 lo = i + 1; hi = len - 1;
关键是对sum == ta, sum > ta, sum < ta
的处理,以及退出while(lo < hi)
之后的处理.
人家想法,咱代码:
\(O(n^2)\) time, \(O(1)\) extra space.
int threeSumClosest(vector<int>& A, int ta) {
const int n = A.size();
int min = INT_MAX; // 存放最接近ta的三个数和
sort(A.begin(), A.end());
for (int i = 0; i < n - 2; i++) {
// 剔除连续值
if (i > 0 && A[i] == A[i - 1]) continue;
int lo = i + 1, hi = n - 1;
// lo==hi 不可以,sum = A[i] + A[lo] + A[hi]会出问题
while (lo < hi) {
int sum = A[i] + A[lo] + A[hi];
// 保存最接近ta的3数之和
min = abs(sum - ta) < abs(min) ? (sum - ta) : min;
if (sum == ta) return ta;
else if (sum > ta) hi--;
else lo++;
}
}
return min + ta; // min = sum - ta, we ask sum now!
}