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) {
sort(nums.begin(), nums.end());
int mini = nums[0]+nums[1]+nums[2];
for (int i = 0; i < nums.size(); i++) {
if (i != 0 && nums[i] > target) break;
if (i != 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j < nums.size(); j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
//if ((!(i == 0 && j == 1) )&& nums[i] + nums[j] > target) break;
for (int k = nums.size() - 1; k > j; k--) {
if (abs(nums[i] + nums[j] + nums[k] - target) < abs(mini - target)) {
mini = nums[i] + nums[j] + nums[k];
}
if (nums[i] + nums[j] + nums[k] - target < 0) break;
}
}
}
return mini;
}
};