[每日一题2020.06.23]leetcode #16 双指针
https://leetcode-cn.com/problems/3sum-closest/submissions/
先对数组进行排序 $ O(nlogn) $ , 然后遍历 + 双指针 $ O (n^2) $
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int absans = 0x3f3f3f3f;
int sum = 0;
for (int i = 0; i < nums.size(); ++i)
{
int l = i + 1;
int r = nums.size() - 1;
while (l < r) {
int tmpsum = nums[i] + nums[l] + nums[r];
int tmpabs = abs(tmpsum - target);
if(tmpabs < absans){
sum = tmpsum;
absans = tmpabs;
}
if (tmpabs == 0) return sum;
else if (tmpsum < target) l++;
else if (tmpsum > target) r--;
}
}
return sum;
}