python算法练习第四天,三数求和

本文记录了作者在解决Python算法练习中关于三数求和的问题时遇到的挑战。最初尝试通过排序和去除重复元素,但导致超时。优化策略改为在遍历时遇到重复元素跳过,确保输出不重复的三数组合。

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

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

 

示例:

给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

我看到题目一开始想法非常简单,先把原先数组排序好,然后先去除数组里的重复元素,然后开始双指针运算,然后就果不其然的超时了

lass Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        res =[]
        i = 0
        for i in range(len(nums)-1):
            if nums[i]==nums[i+1]:
               nums.pop(i)
               i +=1
               break
        for i in range(len(nums)):
            l = i+1
            r = len(nums)-1
            while l < r:
                s = nums[i] + nums[l] +nums[r]
                if s ==0:
                    res.append([nums[i],nums[l],nums[r]])
                if s<0:  
                    l +=1
                if s>0:
                    r -=1
        return res

后来就不用删除重复元素在遇见时跳过就可以了,到后来我发现只要输出的时候不出现重复数组就行那么其实只要找到确定的三组数时将他们的相同元素跳过就可以了。

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        res = [] 
        for i in range(len(nums)-2):
            if i>0 and nums[i] == nums[i-1]: continue
            start = i + 1
            end = len(nums)-1
            

            while start < end:
                su = nums[i] + nums[start] + nums[end]
                if su < 0: 
                    start += 1
                elif su > 0:
                    end -= 1
                else:
                    res.append([nums[i], nums[start], nums[end]])
                    while start < end and nums[start] == nums[start+1]:
                        start += 1
                    while start < end and nums[end] == nums[end-1]:
                        end -= 1
                    start += 1
                    end -= 1
                
        return res 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值