[LintCode 57] 三数之和(Python)

题目描述

给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。

注意事项
在三元组(a, b, c),要求a <= b <= c。
结果不能包含重复的三元组。

样例
如S = {-1 0 1 2 -1 -4}, 你需要返回的三元组集合的是:
(-1, 0, 1)
(-1, -1, 2)

思路

先对序列排序。因为要找三个数,每次遍历固定一个元素,然后根据三数之和调整其他两个数的位置。如果等于0,符合要求;如果大于0,小的数字右移;如果小于0,大的数字左移。遍历过程中注意跳过重复出现的数字。

代码

class Solution:
    """
    @param: numbers: Give an array numbers of n integer
    @return: Find all unique triplets in the array which gives the sum of zero.
    """
    def threeSum(self, numbers):
        # write your code here
        if numbers is None or len(numbers) < 3:
            return []
        res = []
        numbers.sort()
        s = 0
        e = len(numbers) - 1
        while s < e:
            a = numbers[s]
            j = s + 1
            k = e
            while j < k:
                b = numbers[j]
                c = numbers[k]
                if a + b + c == 0:
                    res.append([a, b, c])
                if a + b + c <= 0:
                    while b == numbers[j] and j < k:
                        j += 1
                if a + b + c >= 0:
                    while c == numbers[k] and j < k:
                        k -= 1
            while a == numbers[s] and s < e:
                s += 1
        return res

复杂度分析

时间复杂度 O(n2) ,空间复杂度 O(1)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值