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.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
这道题的解题思路是比较常规的。首先将数组排序,设置三个下标first、second、third分别初始化为0,1,nums.size()-1。
1、如果这三个下标对应的数据之和大于target,那么就把third减一,
2、如果小于target,就把second加一。
3、如果等于target,结束查找,返回这个值。
每当second和third相遇的时候就让first+1,重置second = first + 1,thrid = nums.size() - 1。
这样就可以保证扫描到所有可能的结果,并且算法复杂度为O(n^2).
代码如下:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
if(nums.size()<3) return 0;
int first = 0, second = 1, third = nums.size() - 1;
sort(nums.begin(),nums.end());
int re = nums[0] + nums[1] + nums[2];
for(;first < nums.size()-2;first++){
second = first + 1;
third = nums.size() - 1;
while(second < third){
int temp = nums[first] + nums[second] + nums[third];
if(abs(re - target) > abs(temp - target)) re = temp;
if(temp == target){
return temp;
}
else if(temp < target){
second ++;
}
else{
third --;
}
}
}
return re;
}
};