会做15 threesum就会做这道题 按之前同样的方法就行 非常简单
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
vector<int>::iterator it1, it2;
sort(nums.begin(), nums.end());
int k = (1 << 31) - 1;
int tarn;
int ans = 0;
for (int i = 0; i < nums.size() - 2; ++i) {
while (i > 0 && nums[i - 1] == nums[i]&&i<nums.size()-1)++i;
it1 = nums.begin() + i + 1;
it2 = nums.end() - 1;
tarn = target - nums[i];
while (it1 < it2) {
int sum = *it1 + *it2;
if (sum == tarn) {
return target;
}
else if (sum>tarn) {
--it2;
}
else {
++it1;
}
if (fabs(sum - tarn) < k) {
k = fabs(sum - tarn);
ans = sum+nums[i];
}
}
}
return ans;
}
};