16.最接近的三数之和

2020/10/1

和15题三数之和解题思路差不多

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int len = nums.length;
        int before = nums[0] + nums[1] + nums[len-1];

        for(int i=0; i<len-2; i++){
            if(i>0 && nums[i]==nums[i-1]){
                continue;
            }
            for(int L=i+1, R=len-1;L<R;){
                int sum = nums[i]+nums[L]+nums[R];
                if(sum - target == 0){
                    return sum;
                }else if(sum>target){
                    R--;
                    while(L<R && nums[R]==nums[R+1]){//不用判断R<len-1,因为上一步刚R--;
                        R--; 
                    }
                }else {
                    L++;
                    while(L<R && nums[L]==nums[L-1]){//不用判断L>0,因为上一步刚L++;
                        L++;
                    }
                }
                if(Math.abs(sum - target)<Math.abs(before-target)){
                    before = sum; 
                }
            }
        }
        return before;
    }
}
Last Updated: 4/4/2024