15. 3Sum

这题难度为中等,目前通过率为21.8%

题目:

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]
]
题目大意是找到这n个整数中所有的三个整数和为0的组合。

思路:
对列表进行排序,然后对每个数找另外两个数进行匹配。
步骤:
1.每次选定一个数,判断这个数是否和前一个相同,如果相同说明已经经过计算,则计算下一个以避免浪费时间
PS:由于python的特性,如果位置为负数则从列表后面找,这样对于0号位置的数容易发生错误。例子:[0,0,0]
2.对后面每个数,由于列表是从小到大有序的,所以可以进行夹逼找到和为0的数。如果和小于0,则把左边值往右移,如果大于0,则把右边值往左移。如果等于0,则找到一个答案,加到列表res中,并更新左边值和右边值。

代码:

class Solution:
    def threeSum(self, nums):
        res = []
        nums.sort()
        n = len(nums)
        for i in range(n-2):
            if nums[i] == nums[i-1] and i > 0:
                continue
            l,r = i+1,n-1
            while l<r:
                s = nums[i]+nums[l]+nums[r]
                if s<0:
                    l += 1
                elif s>0:
                    r -= 1
                else:
                    res.append([nums[i],nums[l],nums[r]])
                    while l<r and nums[l] == nums[l+1]:
                        l += 1
                    while l<r and nums[r] == nums[r-1]:
                        r -= 1
                    l += 1
                    r -= 1

        return res

复杂度分析:

外层一个for循环,循环(n-2)次,内层每次找数,最坏情况下要从位置1找到(n-1),需要(n-2)次,因此时间复杂度为
T(n) = (n-2)*(n-2) = O(n^2)

提交:
这里写图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值