[leetcode]16. 最接近的三数之和
程序员文章站
2022-07-15 11:16:30
...
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int res = 0;
int minDiff = INT_MAX/10;
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size(); i++)
{
int left = i + 1, right = nums.size()-1;
while(left < right)
{
int s = nums[i] + nums[left] + nums[right];
if(abs(s - target) < minDiff)
{
minDiff = abs(s - target);
res = s;
if(minDiff == 0)
{
return res;
}
}
if(s < target)
{
left++;
}
else
{
right--;
}
}
}
return res;
}
};