LeetCode: 3Sum

本文深入探讨了经典的三数之和(3Sum)问题,提供了一种高效解决方案,通过定义twoSum函数并结合嵌套循环,实现了在给定数组中寻找三个整数使它们的和为零的目标。文章详细介绍了算法的实现过程,包括特殊情况处理、数组排序、避免重复解等关键步骤。

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

Given an array nums of n integers, are there elements a, b, c in nums 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.

Example:


Given array nums = [-1, 0, 1, 2, -1, -4],

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

本题是2Sum的升级版,要求从list中找出三个int使之相加等于0。我用的方法是定义一个twoSum的函数,遍历数组的同时调用该函数,便可达到计算threeSum的目的。也可以使用嵌套循环(说不定更快)。

  1. 判断特殊情况,list长度小于3直接返回空数组,等于3的话判断相加是否为0
  2. list长度大于3的情况下遍历list第一个到倒数第三个元素,遍历前排序
  3. 将当前元素的value和该元素后面部分的list切片作为参数传入twoSum函数
  4. 遍历twoSum返回值,将当前元素的value添加进去组成triplet,将triplet添加到res中
  5. 返回res

该方法的时间复杂度为O(n2),不过同样是O(n2),经过细节优化依然可以大幅度提升运行速度,比如预先排序后,twoSum可以使用nums的切片作为参数,而不用传入整个list,另外还可以省去最后的判断步骤if item not in res:,直接append就行,因为经过排序和跳过相等的元素之后,不可能再出现重复的情况。经过努力,从6684 ms优化到2188 ms。

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        def twoSum(nums, target):
            res = []
            i = 0
            j = len(nums) - 1
            while i < j:
                if i > 0 and nums[i] == nums[i-1]:
                    i += 1
                    continue
                if j < len(nums) - 1 and nums[j] == nums[j+1]:
                    j -= 1
                    continue
                if nums[i] + nums[j] < target:
                    i += 1
                elif nums[i] + nums[j] > target:
                    j -= 1
                else:
                    res.append([nums[i], nums[j]])
                    i += 1
            if res:
                return res
            else:
                return None
        
        res = []
        l = len(nums)
        if l < 3:
            return []
        if l == 3:
            if sum(nums) == 0:
                res.append(nums)
                return res
            else:
                return []
            
        nums.sort()
        for i, v in enumerate(nums[0:l-2]):
            if i > 0 and v == nums[i-1]:
                continue
            new_nums = nums[i+1:]
            if twoSum(new_nums, 0-v):
                doublet = twoSum(new_nums, 0-v)
                for item in doublet:
                    item.append(v)
                    item.sort()
                    res.append(item)
        
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值