LeetCode 16 最接近的三数之和 - 双指针逼近

LeetCode 16 最接近的三数之和,和三数之和框架一样,只是从"等于 target"变成"最接近 target"。


🟡 最接近的三数之和

找三个数使和最接近 target。[-1,2,1,-4], target=1 → 2(-1+2+1=2)


和第 15 题三数之和几乎一样:排序→固定一个数→双指针。区别是找到一个和之后不返回------因为可能还有更接近的。每次算和三数之和跟 target 的差值,记录最小差值对应的和。

java 复制代码
public int threeSumClosest(int[] nums, int target) {
    Arrays.sort(nums);
    int res = nums[0] + nums[1] + nums[2];  // 初始值

    for (int i = 0; i < nums.length - 2; i++) {
        int left = i + 1, right = nums.length - 1;
        while (left < right) {
            int sum = nums[i] + nums[left] + nums[right];
            if (Math.abs(sum - target) < Math.abs(res - target)) res = sum;
            if (sum < target) left++;
            else if (sum > target) right--;
            else return sum;  // 差 0,不可能更接近了
        }
    }
    return res;
}

和第 15 题比少了去重------不是找所有解,是找最近的一个,重复值不影响。也不用跳过 i 的重复。唯一的新东西是维护"最接近"的逻辑,绝对值差值更小就更新。


更多干货,欢迎访问我的算法笔记网站 codelu.cc,有兴趣的话可以去看看~

这道题你踩过什么坑?或者你用别的语言实现过吗?评论区聊聊,回头复习也方便翻。

相关推荐
风落青芜8 分钟前
数据结构:堆的概念与实现
c语言·开发语言·数据结构·算法
Pniubi4 小时前
01背包类问题-力扣416.分割等和子集
算法·leetcode·职场和发展
文丑颜不良啊15 小时前
LeetCode3041~3060题目解析
java·leetcode
罗西的思考15 小时前
【轻量化复现大模型 / KIMI K3】MTP / EAGLE‑3 模块交互式演示
人工智能·深度学习·算法
文丑颜不良啊16 小时前
LeetCode3101~3120题目解析
java·leetcode
kyle~20 小时前
模型预测控制(MPC)
算法·机器人·控制·传感器
牢姐与蒯21 小时前
cpp算法之哈希
c++·算法·哈希算法
开开心心就好1 天前
两张表格数据对比工具,不用写函数也能查
算法·spring·智能手机·pdf·电脑·intellij-idea·音视频
电科_银尘1 天前
【大模型算法与工程 02】线性回归与逻辑回归:从损失函数到决策边界
算法·逻辑回归·线性回归
玄昌盛不会编程1 天前
LeetCode——2243. 计算字符串的数字和
java·算法·leetcode