和之前3Sum那道题思路一样,刚开始想的是不用每次计算误差,只需要在小于目标和大于目标的转折点出计算两次然后临界的时候计算一次即可,可是实际上和每次都计算误差速度一样的。。。
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
int n = nums.size();
int error = 1<<20, t;
for(int i = 0;i < n-2;i++){
int j = i + 1, k = n - 1;
int minus = 1;
while(j < k){
int sum = nums[i] + nums[j] + nums[k];
if(sum == target) return target;
else if(sum < target){
if(k < n-1 && minus == 0){
if(abs(sum-target) < abs(nums[i]+nums[j]+nums[k+1]-target)){
t = sum-target;
}
else t = nums[i]+nums[j]+nums[k+1]-target;
if(abs(t) < abs(error)) error = t;
}
j++;
minus = 1;
}
else{
if(j > i+1 && minus == 1){
if(abs(sum-target) < abs(nums[i]+nums[j-1]+nums[k]-target)){
t = sum-target;
}
else t = nums[i]+nums[j-1]+nums[k]-target;
if(abs(t) < abs(error)) error = t;
}
k--;
minus = 0;
}
if(j-1 == i) t = nums[i]+nums[j]+nums[j+1]-target;
else t = nums[i]+nums[j]+nums[j-1]-target;
if(abs(t) < abs(error)) error = t;
}
}
return target + error;
}
};
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
int n = nums.size();
int error = 1<<20;
for(int i = 0;i < n-2;i++){
int j = i + 1, k = n - 1;
while(j < k){
int sum = nums[i] + nums[j] + nums[k];
if(sum == target) return target;
else{
if(abs(sum-target) < abs(error)) error = sum - target;
sum < target ? j++ : k--;
}
}
}
return target + error;
}
};