力扣15、三数之和(中等)

1 题目描述

力扣15、三数之和(中等)_第1张图片 图1 题目描述

2 题目解读

        在整数数组nums中,找出三元组,它们的和为0,要求返回所有和为0且不重复的三元组。这是两数之和的扩展题目,可以将三数之和问题。

3 解法一:排序 + 双指针

        将整数数组排序之后,可以简化问题的求解,双指针法是一种常用方法。

3.1 解题思路

        将数组排序之后,使用for循环,把三数之和问题转化为两数之和问题,再使用双指针法。

3.2 设计代码

#include 
#include 
#include 
using namespace std;
class Solution {
public:
    vector> threeSum(vector& nums) {
        int n = nums.size();
        sort(nums.begin(), nums.end());
        vector> ans;
        // 枚举 a
        for (int first = 0; first < n; ++first) {
            // 需要和上一次枚举的数不相同
            if (first > 0 && nums[first] == nums[first - 1]) {
                continue;
            }
            // c 对应的指针初始指向数组的最右端
            int third = n - 1;
            int target = -nums[first];
            // 枚举 b
            for (int second = first + 1; second < n; ++second) {
                // 需要和上一次枚举的数不相同
                if (second > first + 1 && nums[second] == nums[second - 1]) {
                    continue;
                }
                // 需要保证 b 的指针在 c 的指针的左侧
                while (second < third && nums[second] + nums[third] > target) {
                    --third;
                }
                // 如果指针重合,随着 b 后续的增加
                // 就不会有满足 a+b+c=0 并且 b nums;
    for (int i = 0; i < 6; i++)
    {
        nums.push_back(x[i]);
    }
    Solution S;
    vector> ans = S.threeSum(nums);
    for (int i = 0; i < ans.size(); i++)
    {
        for (int j = 0; j < ans[i].size(); j++)
        {
            cout << ans[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

3.3 复杂度分析

  • 时间复杂度:O(n^{2})。两重for循环,且内层for循环与while循环共枚举数组元素一次。
  • 空间复杂度:O(logn)。排序算法的空间复杂度为O(logn)

3.4 提交结果

力扣15、三数之和(中等)_第2张图片 图2 提交结果

4 解题心得

  • 将整数数组排序之后,可以更好地解答题目。
  • sort()排序算法的空间复杂度为O(logn)
  • 双指针法是一种常用的算法题解题方法

你可能感兴趣的:(力扣LeetCode,算法)