时间复杂度O( )
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
if(nums.size()<3)return -1;
for(int i=0;i<nums.size();++i){
for(int j=0;j<nums.size()-i-1;++j){
if(nums[j+1]<nums[j]){
int tmp = nums[j+1];
nums[j+1] = nums[j];
nums[j] = tmp;
}
}
}
int closestNum=nums[0]+nums[1]+nums[2];
for(int i=0;i<nums.size();++i){
if(i>0&&nums[i-1]==nums[i])continue;
int start = i+1;
int end = nums.size()-1;
while(start<end){
if(nums[start]+nums[end]==target-nums[i]){
return target;
}else if(nums[start]+nums[end]>(target-nums[i])){
int sum = nums[start]+nums[end]+nums[i];
if(abs(target-closestNum)>abs(target-sum)){
closestNum=sum;
}
--end;
}else {
int sum = nums[start]+nums[end]+nums[i];
if(abs(target-closestNum)>abs(target-sum)){
closestNum=sum;
}
++start;
}
}
}
return closestNum;
}
int abs(int a){
if(a<0){
a=0-a;
}
return a;
}
};