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:
static bool compare_func(const int d1, const int d2) {
return d1 < d2;
}
int threeSumClosest(vector<int> &num, int target) {
int i, j, k;
int diff, sum;
sort(num.begin(), num.end(), compare_func);
int closest = num[0] + num[1] + num[2];
int diffmin = abs(target - closest);
for(i = 0; i < num.size(); i++) {
for(j = i + 1, k = num.size() - 1; j < k ; ) {
diff = abs(target - num[i] - num[j] - num[k]);
if(diff < diffmin) {
diffmin = diff;
closest = num[i] + num[j] + num[k];
}
if(num[i] + num[j] + num[k] < target) j++;
else if(num[i] + num[j] + num[k] > target) k--;
else return target;
}
}
return closest;
}
};

1635

被折叠的 条评论
为什么被折叠?



