思路:同样是采用前篇文章一样的思想对数组进行两次遍历,时间复杂度只有O(N2)。
class Solution {
public int threeSumClosest(int[] nums, int target) {
int temp;
int len=nums.length;
int flag=0;
Arrays.sort(nums);
temp=target-nums[0]-nums[1]-nums[2];
if(temp<0) temp=0-temp;
for(int first=0;first<len;first++){
int third=len-1;
if(first>0&&nums[first]==nums[first-1]) continue;
for(int second=first+1;second<len;second++){
if(second>first+1&&nums[second]==nums[second-1]) continue;
while(second<third){
if(nums[first]+nums[second]+nums[third]<target){//三数之和小于目标
if(target-nums[first]-nums[second]-nums[third]<temp){
temp=target-nums[first]-nums[second]-nums[third];
flag=1;
}
break;
}else if(nums[first]+nums[second]+nums[third]>target){//三数之和大于目标
if(nums[first]+nums[second]+nums[third]-target<temp){
temp=nums[first]+nums[second]+nums[third]-target;
flag=-1;
}
third--;
}else{
return target;
}
}
if(second==third) break;
}
}
if(flag==1) return target-temp;
else if(flag==-1) return target+temp;
else{
return nums[0]+nums[1]+nums[2];
}
}
}