Leetcode16. 最接近的三数之和

Every day a Leetcode

题目来源:16. 最接近的三数之和

解法1:排序 + 双指针

对数组 nums 进行排序。

枚举 numsi,在区间 (i, n - 1] 内使用双指针 l、r,维护 res = numsi + numsl + numsr 与 target 最接近的值。

代码:

cpp 复制代码
class Solution
{
public:
    int threeSumClosest(vector<int> &nums, int target)
    {
        int n = nums.size();
        int ans = nums[0] + nums[1] + nums[2];
        sort(nums.begin(), nums.end());
        for (int i = 0; i < n; i++)
        {
            int l = i + 1, r = n - 1;
            while (l < r)
            {
                int sum = nums[i] + nums[l] + nums[r];
                if (sum == target)
                    return sum;
                if (abs(sum - target) < abs(ans - target))
                    ans = sum;
                if (sum < target)
                    l++;
                else
                    r--;
            }
        }
        return ans;
    }
};

结果:

复杂度分析:

时间复杂度:O(n2),其中 n 是数组 nums 的长度。我们首先需要 O(nlogn) 的时间对数组进行排序,随后在枚举的过程中,使用一重循环 O(n) 枚举 a,双指针 O(n) 枚举 b 和 c,故一共是 O(n2)。

空间复杂度:O(logn),其中 n 是数组 nums 的长度。

相关推荐
hetao17338371 天前
2026-10-22~23 hetao1733837 的刷题记录
c++·算法
java_nnnn1 天前
LeetCode刷题滑动窗口(串联所有单词的子串+最小覆盖的子串)Java
算法·leetcode·职场和发展
王老师青少年编程1 天前
2025年6月GESP真题及题解(C++三级): 选择题和判断题(题解)
c++·真题·gesp·答案·csp·三级·信奥赛
Navigator_Z1 天前
LeetCode //C - 1301. Number of Paths with Max Score
c语言·算法·leetcode
卡卡~~1 天前
“101计划”核心课程实践教材《数据实验结构指导-C++语言版》题目集
开发语言·c++·学习·算法
lengxuenong1 天前
树状数组 · 信息学学习手册1-求和3个模板
c++·学习·算法·青少年编程
Nuanyt1 天前
LeetCode Hot100 刷题笔记 · 普通数组专题
java·笔记·算法·leetcode
ShineWinsu1 天前
对于Qt:信号与槽的解析
c++·qt·gui·lambda·信号·信号与槽·槽函数
WL学习笔记1 天前
使用string类
c++·后端·string类
xxxiugou1231 天前
链表算法题精讲:从两数相加到K组翻转
数据结构·c++·算法·链表