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:
Code:
<span style="font-size:14px;">class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
const int length = num.size();
int result = num[0]+num[1]+num[2];
sort(num.begin(), num.end());
for (int i = 0; i < length-2; ++i) {
int m = i+1, n = length-1;
while (m < n) {
if (num[i]+num[m]+num[n] == target) return target;
if (abs(num[i]+num[m]+num[n]-target) < abs(result-target)) result = num[i]+num[m]+num[n];
if (num[i]+num[m]+num[n] < target) {
while (m+1 < n && num[m+1] == num[m]) ++m;
++m;
} else if (num[i]+num[m]+num[n] > target) {
while (n-1 > m && num[n-1] == num[n]) --n;
--n;
}
}
while (i < length-2 && num[i+1] == num[i]) ++i;
}
return result;
}
};</span>