Leetcode16. 最接近的三数之和

Every day a Leetcode

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

解法1:排序 + 双指针

对数组 nums 进行排序。

枚举 nums[i],在区间 (i, n - 1] 内使用双指针 l、r,维护 res = nums[i] + nums[l] + nums[r] 与 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 的长度。

相关推荐
端平入洛1 天前
delete又未完全delete
c++
端平入洛2 天前
auto有时不auto
c++
琢磨先生David3 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
哇哈哈20213 天前
信号量和信号
linux·c++
多恩Stone3 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马3 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝3 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll3 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐3 天前
leetcode-最小栈
java·算法·leetcode
weiabc3 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法