题目:
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).
class Solution {
public://时间复杂度O(n^2),空间复杂度O(1)
int threeSumClosest(vector<int>& nums, int target) {
if(nums.size() < 3) return 0;
int res = nums[0]+nums[1]+nums[2];//!!!选最前面的三个元素的和作为res的初衷。我之前很傻的选了INT_MAX,结果当target为负时res-target溢出,看到的现象是abs(res-target)是一个很小很小的负值。另外,因为res是三个int的和,所以为了安全起见,res和sum可以用long long
sort(nums.begin(), nums.end());//排序
for(int i = 0; i < nums.size()-2; ++i){
if(i != 0 && nums[i] == nums[i-1]) continue;//去重
int left = i+1;
int right = nums.size()-1;
while(left < right){
if(left != i+1 && nums[left] == nums[left-1]){//去重
++left;
continue;
}
if(right != nums.size()-1 && nums[right] == nums[right+1]){//去重
--right;
continue;
}
int sum = nums[i]+nums[left]+nums[right];
if(sum == target) return target;
if(abs(sum-target) < abs(res-target)) res = sum;
if(sum < target) ++left;
else --right;
}
}
return res;
}
};
注:
1.每次对整形数做算术运算的是都应该考虑溢出问题,一个比较安全的做法是若返回值要求int型,则尽量使用long long型,然后在返前判断是否超过INT_MAX或INT_MIN
2.这里去重的意义不大,是否去重,对效率的影响不大