思想:
求三数之和最接近target的那组数。
先排序,再左右夹逼。时间复杂度O(n^2)。
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
int result = 0;
int min_gap = INT_MAX;
sort(num.begin(),num.end());
for(auto a = num.begin(); a != prev(num.end(),2); a++) {
auto b = next(a);
auto c = prev(num.end());
while(b<c) {
const int sum = *a+*b+*c;
const int gap = abs(sum-target);
if(gap<min_gap) {
min_gap = gap;
result = sum;
}
if(sum>target) {
c--;
}else {
b++;
}
}
}
return result;
}
};