题目:
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
解答:
先排序后逐个遍历,对于剩下的两个的数利用two pointe即可
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int res = 0;
int size = nums.size();
int gap = INT_MAX;
for(int i = 0;i < size - 2;i++)
{
int l = i + 1;
int r = size - 1;
while(l < r)
{
int t = nums[l] + nums[r] + nums[i];
if(abs(t - target) < gap)
{
res = t;
gap = abs(t - target);
}
if(gap == 0) //插入之后时间减少了8ms....
break;
if(t < target)
l++;
else
r--;
}
}
return res;
}
};