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.
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
typedef vector<int>::size_type sz;
sort(nums.begin(), nums.end());
int ret = nums[0] + nums[1] + nums[2];
for (sz i = 0; i != nums.size() - 2; ++i) {
int twoSum = target - nums[i];
sz j = i + 1;
sz k = nums.size() - 1;
while (j < k) {
int tmpSum = nums[j] + nums[k];
int tmp = nums[i] + tmpSum;
if (abs(tmp - target) < abs(ret - target))
ret = tmp;
if (tmpSum < twoSum) {
while(j < k && nums[j + 1] == nums[j]) ++j;
++j;
} else if (tmpSum > twoSum) {
while(j < k && nums[k - 1] == nums[k]) --k;
--k;
} else {
return target;
}
}
while (i + 1 != nums.size() - 2 && nums[i + 1] == nums[i]) ++i;
}
return ret;
}
};