python--lintcode57.三数之和

描述

给出一个有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)


我只能说这一题很有意思,这一题是上一题的升级版,具体可见:https://blog.csdn.net/wenqiwenqi123/article/details/80791277

那么这一题怎么做呢?就是先排序,使得a<=b<=c。因为a+b+c=0也就是说b+c=-a,所以需要遍历一遍数组去找所有的a值,这样跟上一题就一样了,target=-a而已。但是因为我们使得a<=b<=c,那么我们在遍历整个数组的时候,只需要去a的右边找b和c的值。

需要特别注意的是,为了使得在取数字的时候不重复,需要加几个while和if判断一下此数字是否和前一个数字相同:

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

        def twoSum(nums, target):
            # write your code here
            nums = sorted(nums)
            start, end = 0, len(nums) - 1
            tworesult=[]
            while (start < end):
                # 防止数字重复选取
                while(start<end and start!=0 and nums[start]==nums[start-1]):
                    start+=1
                while(start<end and end!=len(nums)-1 and nums[end]==nums[end+1]):
                    end-=1
                if(start==end):break

                sum = nums[start] + nums[end]
                if (sum < target):
                    start += 1
                    continue
                elif (sum > target):
                    end -= 1
                    continue
                else:
                    tworesult.append([nums[start], nums[end]])
                    start+=1
                    end-=1
            return tworesult

        numbers=sorted(numbers)
        totalresult=[]
        for i in range(len(numbers)):
            # 防止数字重复选取
            if(i!=0 and numbers[i]==numbers[i-1]):
                continue

            if(i+1<len(numbers)):
                result=twoSum(numbers[i+1:],-numbers[i])
                for j in range(len(result)):
                    if(numbers[i]+result[j][0]+result[j][1]==0):
                        totalresult.append([numbers[i]]+result[j])
                continue
        return totalresult



s = Solution()
print(s.threeSum([1,0,-1,-1,-1,-1,0,1,1,1]))
# [-2,-3,5,-1,-4,5,-11,7,1,2,3,4,-7,-1,-2,-3,-4,-5]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哎呦不错的温jay

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值