lintcode练习-57. 三数之和

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

 

实现代码:

class Solution:
    ans = []
    """
    @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
        #从大到小排序,想要为0,必须要有正有负
        numbers.sort()
        right = len(numbers) -1 
        # b+c = -a, a<=b<=c
        for a in range(len(numbers) - 2):
            if a > 0 and numbers[a-1] == numbers[a]:
                continue
            left = a + 1
            self.twoSum(numbers, left, right, -numbers[a])
        
        return self.ans
    
    def twoSum(self, numbers, left, right, target):
        while left < right:
            summation = numbers[left] + numbers[right]
            if summation == target:
                self.ans.append((-target, numbers[left], numbers[right]))
                left, right = left + 1, right - 1
                #如果和前一个一样,就重复了
                while left < right and numbers[left] == numbers[left - 1]:
                    left += 1
                while left < right and numbers[right] == numbers[right + 1]:
                    right -= 1
            elif summation < target:
                left += 1
            else:
                right -= 1
        
        

猜你喜欢

转载自blog.csdn.net/qq_36387683/article/details/81428381