public class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int lastDistance=Integer.MAX_VALUE;
int last=lastDistance;
int result=0;
out:for(int i=0;i<nums.length;i++)
{
if(last==nums[i])
{
continue;
}
last=nums[i];
int j=i+1,k=nums.length-1;
while(j<k)
{
int temp=(target-nums[i]-nums[j]-nums[k]);
if(Math.abs(temp)<lastDistance)
{
lastDistance=Math.abs(temp);
result=target-temp;
}
if(temp>0)
{
j++;
}
else if(temp<0)
{
k--;
}
else
{
break out;
}
}
}
return result;
}
}
leetcode 3Sum Closest
三数之和最接近目标值
最新推荐文章于 2020-01-16 15:31:01 发布
本文介绍了一个Java实现的解决方案,用于寻找数组中三个数相加最接近给定目标值的组合。通过先对数组进行排序,然后使用双指针技巧遍历数组来寻找最优解。
212

被折叠的 条评论
为什么被折叠?



