题目
题目源码
public class Solution
{
public int threeSumClosest(int[] nums, int target)
{
Arrays.sort(nums);
int result=nums[0]+nums[1]+nums[2];
int dis=result-target;
int len=nums.length;
for(int i=0;i<len-2;i++)
{
if(i>0 && nums[i]==nums[i-1])
{
continue;
}
int j=i+1;int m=len-1;
int goal=target-nums[i];
while(j<m)
{
if(Math.abs(dis)>Math.abs(nums[j]+nums[m]-goal))
{
dis=nums[j]+nums[m]-goal;
result=nums[i]+nums[j]+nums[m];
}
if(nums[j]+nums[m]==goal)
{
return target;
}
else if(nums[j]+nums[m]<goal)
{
j++;
while (j<m && nums[j]==nums[j-1])
{
j++;
}
}
else
{
m--;
while (j<m && nums[m]==nums[m+1])
{
m--;
}
}
}
}
return result;
}
}
网友评论