15.3Sum(python)

系统 1256 0

1.Description:

 

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]
]
          

2.Ideas:

 

这道题需要从一个列表中选出所有满足和为0的三元组,且要求去重,最简单的思路就是暴力的3层循环,这样肯定会超时。我们可以简单的进行分析,三个数的和为零,可以先确定一个数,然后再确定另外两个数,使另外两个数的和为第一个确定数的相反数,这样就可以将O(n^3)转为O(n^2)。我们可以让第一个确定的数为一个不大于0的数,而且,因为最快的排序算法的时间复杂度是O(nlogn)

3.Code:

            
              class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        L = []
        nums.sort()
        length = len(nums)
        if(length<3):
            return L
        for i in range(length-2):
            if(nums[i]>0):#三个大于0的数之和不会是0
                break
            if(i>0 and nums[i]==nums[i-1]):#去掉重复的情况
                continue
            target = -nums[i]
            left = i+1
            right = length-1
            while left < right:
                if(nums[left]+nums[right]==target):
                    temp = []
                    temp.append(nums[i])
                    temp.append(nums[left])
                    temp.append(nums[right])
                    L.append(temp)
                    left+=1
                    right-=1
                    while left
              
                
                  < right:
                        left += 1
                        if nums[left] > nums[left - 1]: break
                else:
                    while left < right:
                        right -= 1
                        if nums[right] < nums[right + 1]: break
        return L
                
              
            
          

4.Result:

15.3Sum(python)_第1张图片


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论