class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int n = nums.size();
sort(nums.begin(), nums.end());
int ans=nums[0]+nums[1]+nums[2];
if(n==3)return ans;
for (int first = 0; first < n-2; ++first) {
if (first > 0 && nums[first] == nums[first - 1])
continue;
int second = first + 1;
int third = n - 1;
while(1) {
if (second == third) break;
if (abs(nums[second]+nums[third]+nums[first]-target) < abs(ans-target)) {
ans=nums[second]+nums[third]+nums[first];
if(ans==target) return target;
}
if(nums[second]+nums[third]+nums[first]-target>0)
--third;
else ++second;
}
}
return ans;
}
};
由第十五题的官方解法稍加修改而来。依旧使用双指针。双指针真好用。