【两次过】【双指针】Lintcode 533. 两数和的最接近值

本文介绍了一种使用双指针法解决寻找整数数组中两个数字,使其和最接近给定目标的问题。通过排序数组并使用双指针从两端向中间移动的方式,有效地在O(nlogn)的时间复杂度内找到了最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定整数数组num,从中找到两个数字使得他们和最接近target,返回两数和与 target的差的 绝对值

样例

样例1

输入: nums = [-1, 2, 1, -4] 并且 target = 4
输出: 1
解释:
最小的差距是1,(4 - (2 + 1) = 1).

样例2

输入: nums = [-1, -1, -1, -4] 并且 target = 4
输出: 6
解释:
最小的差距是6,(4 - (- 1 - 1) = 6).

挑战

Do it in O(nlogn) time complexity.


解题思路:

双指针法。

public class Solution {
    /**
     * @param nums: an integer array
     * @param target: An integer
     * @return: the difference between the sum and the target
     */
    public int twoSumClosest(int[] nums, int target) {
        // write your code here
        Arrays.sort(nums);
        int l = 0;
        int r = nums.length-1;
        int res = Integer.MAX_VALUE;
        
        while(l < r){
            res = Math.min(res, Math.abs(target - nums[l] - nums[r]));
            
            if(nums[l] + nums[r] < target)
                l++;
            else
                r--;
        }
        
        return res;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值