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;
    }
};
相关推荐
郝学胜-神的一滴8 小时前
Effective STL 条款 07:指针容器销毁前先删除
开发语言·c++·vscode·leetcode·rpc·visual studio
CoderYanger8 小时前
A.每日一题:2243. 计算字符串的数字和
java·开发语言·程序人生·leetcode·面试·蓝桥杯·学习方法
青少儿编程课堂11 小时前
蓝桥杯真题解析:三维偏序的CDQ分治(全国青少年信息素养大赛与电子学会编程考级)
c++·python·算法·bfs·信息学竞赛
Navigator_Z12 小时前
LeetCode //C - 1323. Maximum 69 Number
c语言·算法·leetcode
geovindu12 小时前
python:Lasso
开发语言·后端·python·算法
AAA修煤气灶刘哥13 小时前
同一个模型,为什么还要专门练一遍怎么用工具?
人工智能·后端·算法
AAA修煤气灶刘哥14 小时前
两个 Agent 各自改得都对,合在一起为什么出错?
人工智能·后端·算法
电科_银尘14 小时前
【大模型算法与工程 34】QLoRA:量化底座上的低秩训练
人工智能·算法·机器学习
专注仿真14 小时前
智能体训练:模仿学习与 MCTS 算法详解与实战
算法·强化学习·仿真·afsim智能体·仿真训练