LeetCode 3Sum (Two pointers)

本文探讨了如何找出数组中三个数相加等于0的所有不重复组合。通过优化从三层循环到双指针方法,时间复杂度从O(logN*N^2)降低至O(N^2)。此外,还介绍了如何利用Map来避免重复组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
找出一个数组中的三个数,使这三个数的和为0。输出所有的组合,不能重复。

解法

最简单的思路就是跑一个三层循环,暴力枚举所有组合,很显然会超时。

然后考虑排序后跑两层循环,第三层改用二分查找,即确定前两个数后用二分来搜第三个数,时间复杂度降到了O(logN * N^2),还是会超时。

最后,采用了Two Sum这一题的办法,遍历第一个数,然后剩下的两个数用双指针算法来找,这样时间复杂度就降到了O(N^2)

还有一个问题是判重,这里采用的办法是将三个数拼接起来成为一个数,比如【-1,0,1】就被保存成-101,用Long Long来存,然后放到一个Map里,每次选取新答案时都判断一下这样的组合是不是能在Map里找到。

class Solution
{
public:
    vector<vector<int>> threeSum(vector<int>& nums)
    {
        map<long long,bool> vis;
        sort(nums.begin(),nums.end());

        vector<vector<int>> rt;
        for(int i = 0;i < nums.size();i ++)
        {
            if(nums[i] > 0)
                break;
            int j = i + 1;
            int k = nums.size() - 1;
            while(j < k)
            {
                if(nums[i] + nums[j] + nums[k] == 0)
                {
                    long    long    box = abs(nums[i]); // 判重
                    int temp = abs(nums[j]);
                    while(temp)
                    {
                        box *= 10;
                        temp /= 10;
                    }
                    box += abs(nums[j]);
                    temp = abs(nums[k]);
                    while(temp)
                    {
                        box *= 10;
                        temp /= 10;
                    }
                    box += abs(nums[k]);
                    if(nums[i] * nums[j] * nums[k] < 0)
                        box = -box;

                    if(vis.find(box) == vis.end())
                    {
                        vis[box] = true;
                        rt.push_back({nums[i],nums[j],nums[k]});
                    }
                    j ++;
                }

                if(nums[i] + nums[j] + nums[k] < 0)
                    j ++;
                else    if(nums[i] + nums[j] + nums[k] > 0)
                    k --;
            }
        }
        return  rt;
    }
};

转载于:https://www.cnblogs.com/xz816111/p/5856839.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值