leetcode16--最接近的三数之和

1. 题意

求最接近的三数之和
最接近的三数之和

2. 题解

三数之和类似

cpp 复制代码
class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {

        sort(nums.begin(), nums.end());

        int sz = nums.size();

        int sum = nums[0] + nums[1] + nums[2];


        for (int i = 0;i < sz; ++i) {
            int lp = i + 1;
            int rp = sz - 1;
    
            if ( i && nums[i - 1] == nums[i])
                continue;

            int tot ;
            while (lp < rp) {
                tot = nums[i];
                tot += nums[lp] + nums[rp];

                if ( abs( tot - target) < abs(sum - target))
                    sum = tot;

                if ( tot < target) {
                    ++lp;
                }
                else {
                    --rp;
                }
            }
        }

        return sum;
    }
};
相关推荐
菜鸡儿齐2 小时前
leetcode-有效的括号
linux·算法·leetcode
We་ct2 小时前
LeetCode 102. 二叉树的层序遍历:图文拆解+代码详解
前端·算法·leetcode·typescript
历程里程碑2 小时前
26信号处理一:从闹钟到进程控制的奥秘
linux·运维·服务器·开发语言·c++·算法·排序算法
Gofarlic_OMS2 小时前
LS-DYNA许可证全局状态及集群计算资源使用可视化监控大屏
运维·开发语言·算法·matlab·自动化
载数而行5202 小时前
算法系列4之插入排序
数据结构·c++·算法·排序算法
会员果汁2 小时前
二分搜索-C
c语言·算法
智者知已应修善业2 小时前
【查找指定字符串首位置与数量不区分大小写完整匹配】2025-5-3
c语言·c++·经验分享·笔记·算法
fengfuyao9852 小时前
基于局部均值分解(LMD)的MATLAB信号分解程序实现
算法·matlab·均值算法
㓗冽2 小时前
分割数字并排序(字符串)-基础题103th + A == B ?(字符串)-基础题104th + 母牛制造的回文(字符串)-基础题105th
算法
问好眼3 小时前
《算法竞赛进阶指南》0x01 位运算-4.最短Hamilton路径
c++·算法·动态规划·位运算·信息学奥赛