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;
    }
};
相关推荐
橘颂TA17 小时前
【剑斩OFFER】算法的暴力美学——点名
数据结构·算法·leetcode·c/c++
MATLAB代码顾问18 小时前
多种时间序列预测算法的MATLAB实现
开发语言·算法·matlab
高山上有一只小老虎19 小时前
字符串字符匹配
java·算法
愚润求学20 小时前
【动态规划】专题完结,题单汇总
算法·leetcode·动态规划
林太白20 小时前
跟着TRAE SOLO学习两大搜索
前端·算法
ghie909020 小时前
图像去雾算法详解与MATLAB实现
开发语言·算法·matlab
云泽80821 小时前
从三路快排到内省排序:探索工业级排序算法的演进
算法·排序算法
weixin_4684668521 小时前
遗传算法求解TSP旅行商问题python代码实战
python·算法·算法优化·遗传算法·旅行商问题·智能优化·np问题
·白小白21 小时前
力扣(LeetCode) ——43.字符串相乘(C++)
c++·leetcode
FMRbpm1 天前
链表5--------删除
数据结构·c++·算法·链表·新手入门