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 的长度。

相关推荐
clint4562 天前
C++进阶(1)——前景提要
c++
夜悊2 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴2 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0013 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾3 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you3 天前
constexpr函数
c++
凡人叶枫3 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫3 天前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss3 天前
BRpc使用
c++·rpc
-森屿安年-3 天前
63. 不同路径 II
c++·算法·动态规划