leetcode 16. 3Sum Closest(最近的三个数之和)

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example 1:

Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Constraints:

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

给出一个数组,一个target数字,让找出3个数字的和,使得这个和与target最接近
每个数组都有一个解

思路:
涉及到3 Sum的问题,还是用3 Sum的思路,选一个数字,剩下的用2 Sum,以解决遍历所有和的问题
与target最接近表示|sum - target| 越小,注意这个是绝对值的差,所以要用一个变量保存最小的绝对值差,当一个更小的绝对值差出现时,就更新最小绝对值的差,并保存当前3个数字的和
先把数组排序,2 Sum就可以用双指针解决

2 Sum部分用双指针的话,只凭绝对值的差不能判断移动左指针还是右指针,所以移动指针的时候要用3个数字的和与target比较

注意遍历第一个数字的时候只需遍历到数组长度-2,因为保证后面还有至少两个数字

    public int threeSumClosest(int[] nums, int target) {
        if(nums == null || nums.length < 3) {
            return -1;
        }
        
        int result = nums[0] + nums[1] + nums[2];
        int diff = Math.abs(target - result);
        int n = nums.length;
        Arrays.sort(nums);
        
        for(int i = 0; i < n-2; i ++) {
            int left = i + 1;
            int right = n - 1;
            while(left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                int newDiff = Math.abs(sum - target);
                if(newDiff == 0) {
                  return target;
                } else if(newDiff < diff) {
                  diff = newDiff;
                  result = sum;
                }
            
                if(sum < target) {
                    left ++;
                } else {
                    right --;
                }
            }
            
        }
        
        return result;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值