15. 三数之和

简介: 15. 三数之和

15. 3Sum


想法

3个for循环的解法肯定是超时的,考虑使用双指针的方法。要特别注意的是不能重复。例如nums = [-1,0,1,2,-1,-4]有2个-1,需要将第二个-1组成的[-1,0,1]剔除。


基本解法

class Solution
{
public:
    vector<vector<int>> threeSum(vector<int> &nums)
    {
        vector<vector<int>> ans;
        int N = nums.size();
        sort(nums.begin(), nums.end());
        for (int first = 0; first < N - 2; first++)
        {
            if (nums[first] > 0)
            {
                return ans;
            }
            // first去重
            if (first > 0 && nums[first] == nums[first - 1])
            {
                continue;
            }
            int second = first + 1;
            int third = N - 1;
            while (second < third)
            {
                if (nums[second]+nums[third]>-nums[first])
                {
                    third--;
                }
                else if (nums[second]+nums[third]<-nums[first])
                {
                    second++;
                }
                else
                {
                    ans.push_back({nums[first], nums[second], nums[third]});
                    second++;
                    third--;
                    // second去重
                    while (second < third && nums[second] == nums[second - 1])
                    {
                        second++;
                    }
                    //third去重
                    while (third > second && nums[third] == nums[third + 1])
                    {
                        third--;
                    }
                }
            }
        }
        return ans;
    }
};


这里的双指针是同时滑动的,也就是说比较后2数与首数的大小关系,大于首数说明整体大于0,所以要移动尾指针,反之亦然。这里有一个要注意的点是,当我使用int s = nums[first] + nums[second] + nums[third],然后比较s与0的大小关系时,总有3个判例超时。后来不写这一步,直接nums[first] + nums[second] + nums[third]与0比较就能通过。就挺离谱的。

目录
相关文章
|
12月前
|
算法
【算法专题突破】双指针 - 三数之和(7)
【算法专题突破】双指针 - 三数之和(7)
44 0
|
2月前
|
算法
LeetCode第15题三数之和
该文章介绍了 LeetCode 第 15 题三数之和的解法,通过先对数组排序,使用双指针减少循环层数,依次取一个元素作为第一个元素,通过双指针法寻找符合条件的三元组,并进行去重处理,同时总结了 2 数之和可使用哈希表解决,超过 2 数之和可使用双指针减少循环次数。
LeetCode第15题三数之和
|
5月前
15. 三数之和
15. 三数之和
33 3
|
4月前
15.三数之和
15.三数之和
|
5月前
|
Java C++ Python
leetcode-15:三数之和
leetcode-15:三数之和
35 0
|
5月前
|
算法 C++
(C++)三数之和--双指针法
(C++)三数之和--双指针法
36 0
LeetCode: 16. 最接近的三数之和 | 双指针专题
【LeetCode: 16. 最接近的三数之和 | 双指针专题 】
53 1
|
存储
每日一题——三数之和(双指针)
每日一题——三数之和(双指针)
|
算法 测试技术
leetcode:15.三数之和
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
74 0
|
测试技术 索引
leetcode_15. 三数之和
题目链接: 15. 三数之和 据说华为的机试经常考这题,而且这道题也是扩展性极强的一道题,你可以看到18. 四数之和,或者人为修改的五数之和,六数之和,乃至n 数之和,也就是
leetcode_15. 三数之和