题目链接:
https://leetcode-cn.com/problems/3sum-closest/
题目描述:
题解:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int ans = INT_MAX;
for(int i = 0; i < nums.size() - 2; i++)
{
int l = i + 1;
int r = nums.size() - 1;
while(l < r)
{
int temp = nums[i] + nums[l] + nums[r] - target;
if(abs(temp ) < abs(ans ))
{
ans = temp;
}
if(temp > 0)
{
r--;
}else if(temp < 0)
{
l++;
}else
{
return target;
}
}
}
return ans + target;
}
};