Leetcode 15:3Sum

本文深入探讨了经典的三数之和(3Sum)问题,给出了一种高效的解决方案。通过先排序,然后使用双指针技巧,避免了重复解,实现了在O(n^2)时间复杂度内找到所有唯一三元组,使它们的和为零。

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

Given an array nums of n integers, are there elements abc 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问题类似,首先将数组排序后,每次先固定一个数,剩下的就变成了2Sum问题。注意for循环里第一个if,如果nums[i]与nums[i-1]相同的话,可以直接跳过,因为在nums[i-1]已经处理过了。还有最后一个else的部分,要跳过连续重复的部分,start和end都要跳过。这样是为了确保题目要求中结果不重复,如果不这么做会超时

class Solution:
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums=sorted(nums)
        print(nums)
        ans=[]
        for i in range(len(nums)-2):
            if i>0 and nums[i]==nums[i-1]:
                continue
            tmp=nums[i]
            start=i+1
            end=len(nums)-1
            point=0-tmp
            while start<end and start<len(nums):
                t=nums[start]+nums[end]
                if t<point:
                    start+=1
                elif t>point:
                    end=end-1
                else:
                    ans.append([tmp,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=end-1
                    start+=1
                    end=end-1
        return ans

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值