class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int n = nums.size();
sort(nums.begin(), nums.end());
int best = nums[0] + nums[1] + nums[2];
for (int first = 0; first < n - 2; first++)
{
if (first > 0 && nums[first] == nums[first - 1])
{
continue;
}
int second =first + 1, third = n - 1;
while (second < third)
{
if (second > first + 1 && nums[second] == nums[second - 1])
{
second++;
continue;
}
int tmp_target = nums[first] + nums[second] + nums[third];
if (tmp_target == target)
{
return target;
}
else
{
best = abs(best-target) < abs(target - tmp_target) ? best : tmp_target;
if (target < tmp_target)
{
third--;
}
else
{
second++;
}
}
}
}
return best;
}
};
08-30
08-30
08-30
08-30