力扣 16 最接近的三数之和

在这里插入图片描述
在这里插入图片描述
对于三个数的查找我们一般会采用for循环加双指针。第一个数组下标为循环变量i,第二个数组下标为left,第三个数组下标为right。我们需要先对数组排序。将最小的和先初始化为数组的前三个之和。

class Solution {
    
    
    public int threeSumClosest(int[] nums, int target) {
    
    
    Arrays.sort(nums);
    int sum=nums[0]+nums[1]+nums[2];
    for(int i=0;i<nums.length-2;i++)
    {
    
    
        int left=i+1;//左指针
        int right=nums.length-1;//右指针
        
        while(left<right)
        {
    
    
            int temp=nums[i]+nums[left]+nums[right];//临时对比变量
          //如果当前的和与target的差小于之前sum与target的差,则就更新sum
            if(Math.abs(temp-target)<Math.abs(sum-target)){
    
    
                sum=temp;
            }
            //如果temp大于target就说明是right太大,缩小right,
            //因为left只能向左移,只能是增大的
            if(temp>target)
            {
    
    
                right--;
            }
            //同理
            else if(temp<target)
            {
    
    
                left++;
            }
            else{
    
     //temp==target,说明找到和为target的,直接返回
                return sum;
            }
        }
    }
    return sum;    
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_51656756/article/details/121688145