LeetCode 16. 3Sum Closest

本文深入解析3SumClosest算法,旨在从数组中找出三数之和最接近目标值的解决方案。通过双指针技巧优化搜索过程,实现高效求解。文章提供了详细的Java代码示例,展示了如何通过排序和迭代寻找最优解。

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

题目

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:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

这道题要从一个数组中找到三个数字相加之和离target最近,其实跟3sum一毛一样的,只是把return改成了比较sum和target之间差距多少,懂了3sum以后做这道题是easy模式,所以就不多说了,会3sum一定会这道题,所以复习的时候去看3sum吧。

Runtime: 4 ms, faster than 78.56% of Java online submissions for 3Sum Closest.

Memory Usage: 38.4 MB, less than 6.67% of Java online submissions for 3Sum Closest.

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        if (nums.length < 3) {
            throw new IllegalArgumentException("array length smaller than 3");
        }
        
        int result = nums[0] + nums[1] + nums[2];
        
        for (int i = 0; i < nums.length - 2; i++) {
            int pStart = i + 1;
            int pEnd = nums.length - 1;
            
            while (pStart < pEnd) {
                int sum = nums[pStart] + nums[pEnd] + nums[i];
                if (sum > target) {
                    pEnd--;
                } else if (sum < target) {
                    pStart++;
                } else {
                    return target;
                }
                if (Math.abs(sum - target) < Math.abs(result - target)) {
                    result = sum;
                }
            }
        }
        
        return result;
    }
}

2024.6.27

就,咱也不知道,为啥这次还做错了。3sum倒是真记住了,但是不知道最近的脑子为啥给result initialize的时候想成了随便设一个值都行……最后debug了好久,fine。

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int result = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length; i++) {
            int low = i + 1;
            int high = nums.length - 1;
            while (low < high) {
                int sum = nums[i] + nums[low] + nums[high];
                if (sum == target) {
                    return target;
                } else if (sum < target) {
                    low++;
                } else {
                    high--;
                }
                if (Math.abs(target - sum) < Math.abs(target - result)) {
                    result = sum;
                }
            }
        }
        return result;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值