解题思路:
- 参考三数之和
- 类似动态规划问题
- 先排序,利用三数之和得到的sum与target求diff,如果diff减小,更新这三个数;
- 根据diff的变化改变指针,如果diff=0,直接返回;如果diff>0,需要右指针–;如果diff<0,需要左指针++;
C++实现如下:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target)
{
sort(nums.begin(), nums.end());
int diff_temp = INT_MAX;
vector<int> ans(3);
for(int i = 0; i < nums.size(); ++i)
{
int j = i + 1;
int k = nums.size() - 1;
while(j < k)
{
int sum = nums[i] + nums[j] + nums[k];
int diff = target - sum;
if(abs(diff) < diff_temp)
{
diff_temp = abs(diff);
ans.clear();
ans[0] = nums[i];
ans[1] = nums[j];
ans[2] = nums[k];
}
if(diff == 0)
{
ans[0] = nums[i];
ans[1] = nums[j];
ans[2] = nums[k];
return target;
}
else if(diff < 0)
--k;
else
++j;
}
}
return ans[0] + ans[1] + ans[2];
}
};