# 16. 3Sum Closest

#### 问题描述

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

#### 代码

class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
if (nums.size() < 3)
return 0;
int cloest = nums[0] + nums[1] + nums[2];
sort(nums.begin(), nums.end());
for (int first = 0; first < nums.size() - 2; first++){
if (first > 0 && nums[first] == nums[first - 1]) continue;
//same output, pass.
int second = first + 1;
int third = nums.size() - 1;
while (second < third){
int cur = nums[first] + nums[second] + nums[third];
if (cur == target)
return cur;
if (abs(cur - target) < abs(cloest - target)){
cloest = cur;
}
if (cur < target)
second++;
else
third--;
}
}
return cloest;
}
};

#### 反思

sort非常重要，对于相同情况的判断可以减轻计算量。还可以计算头三个和后三个的和来快速解决一些特殊的测试用例。

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120