[Leetcode] 15. 3Sum 解题报告

本文探讨了如何在给定的整数数组中找到所有唯一且加和为零的三元组,通过排序和双指针技巧实现了高效查找,避免了重复结果。

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

题目

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

思路

       对于3Sum而言,即使原数组是排好序的,也需要至少O(n^2)的时间复杂度。而排序的时间复杂度是O(nlogn),不影响最终的时间复杂度,所以我们可以首先对数组进行排序,然后采用双指针扫描的方法实现第二层循环。整个算法的时间复杂度就是O(n^2),空间复杂度为O(1)。

       为了防止出现重复结果,需要注意一旦相邻元素相同,则后续元素应该跳过。详见下面代码的注释部分。另外一种简单方法是,将nums转存到一个set<int>中,然后在set<int>中完成两遍扫描。这样做的好处在于set不仅可以自动排序,而且可以自动去重。

代码

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) 
    {
        vector<vector<int>> ret;
        if(nums.size() < 3) 
            return ret;
        sort(nums.begin(), nums.end());
        long previous = LONG_MAX;       // make sure previous is not equal to any element
        for(int i = 0; i < nums.size() - 2; ++i)
        {
            int target = - nums[i];
            if(target == previous)                          // make sure the first element is not duplicate
                continue;
            int j = i + 1;
            int k = nums.size() - 1;
            while(j < k)
            {
                if(nums[j] + nums[k] == target)
                {
                    ret.push_back(vector<int>{nums[i], nums[j], nums[k]});
                    while(j < k && nums[j] == nums[j+1])    // make sure the second element is not duplicate
                        j++;
                    while(j < k && nums[k] == nums[k-1])    // make sure the third element is not duplicate
                        k--;
                    j++;
                    k--;
                }
                else if(nums[j] + nums[k] < target)
                {
                    j++;
                }
                else
                {
                    k--;
                }
            }
            previous = target;
        }
        return ret;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值