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).
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int size = nums.size();
if (size < 3) {
return 0;
}
int sum = 0;
unsigned int diff = 0xffffffff;
std::sort(nums.begin(), nums.end());
for (int i = 0; i < size - 2; ++i) {
if (i > 0 && nums[i] == nums[i-1]) {
continue;
}
int j = i + 1;
int k = size - 1;
for (; j < k; ) {
int tmp = nums[i] + nums[j] + nums[k];
int tmp0 = (tmp - target);
if (tmp0 == 0) { return tmp; }
if (abs(tmp0) < diff) {
diff = abs(tmp0);
sum = tmp;
}
if (tmp0 > 0) {
--k;
} else {
++j;
}
}
}
return sum;
}
};