LeetCode's closest sum of three numbers Java double pointer

Title description :
Given an array nums including n integers and a target value target. Find the three integers in nums so that their sum is closest to target. Returns the sum of these three numbers. Assume that there is only one answer for each set of inputs.

Example:

输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2)

prompt:

3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4

Source: LeetCode
Link: https://leetcode-cn.com/problems/3sum-closest

Similar topics:

Sansanowa

Sum of four

Ideas

这题跟三数之和有点相似,不同点就是要在缩进的过程
要如何判断此时的三数之和与目标值相差最小

1.用双指针之前将数组排序,不然双指针没法使用;

2 选取一个点i表示a的位置,然后用left和right分
别表示b和c的位置,left应该在i后面,所以left的
初始值为i+1,right就放在数组最后面,在判断过程
中两头缩进;

3.在选取i的时候从前往后找,如果此时
nums[i]+nums[l]+nums[r]>targetr r--,
如果num[i]+nums[l]+nums[r]<target,l++,
如果nums[i]+nums[l]+nums[r]==target,就
直接return target

3.1 int sum=nums[i]+nums[l]+nums[r]
如果sum>targetr r--,或者sum<target l++
这个时候判断一下,此时的sum与target的距离
是否比上一次lastsum与target的距离小,如果
比上一次的小就更新答案,没有直接则继续缩进,
继续判断;

Code :

class Solution {
    
    
    public int threeSumClosest(int[] nums, int target) {
    
    
        int length=nums.length;
        int ans=999999;
         int lastsum=99999;
        Arrays.sort(nums);
        for(int i=0;i<length-2;i++){
    
    
            
            int l=i+1;
            int r=length-1;
            
            while(l<r){
    
    
                int sum=nums[i]+nums[l]+nums[r];
                if(sum>target){
    
    
                    r--;
               if(lastsum> Math.abs(target-sum))
               {
    
    
                   lastsum=Math.abs(target-sum);
                   ans=sum;
               }
              }
               else if(sum<target){
    
    
                   l++;
                 if(lastsum> Math.abs(target-sum))
               {
    
    
                 
                   lastsum=Math.abs(target-sum);
                   ans=sum;
               }
               }
            else if(sum==target){
    
    
                    return sum;
            }

            }
        }
        return ans;
    }
}

Guess you like

Origin blog.csdn.net/qq_44844588/article/details/108146875