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:
    """
    @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
        length = len(numbers)
        if length < 3 : 
            return []
        results = []
        numbers.sort()
        for i in range(0, length-2):
            if numbers[i] > 0: 
                break
            if i and numbers[i]==numbers[i-1]:
                continue
            target = -numbers[i]
            left, right = i+1, length-1
            while left < right :
                if numbers[right] + numbers[left] == target:
                    results.append([numbers[i], numbers[left], numbers[right]])
                    left += 1
                    right -= 1
                    while left < right and numbers[left] == numbers[left-1]: 
                        left += 1
                    while right < left and numbers[right] == numbers[right-1]: 
                        right -= 1
                elif numbers[right] + numbers[left] < target:
                    left += 1
                    while left < right and numbers[left] == numbers[left-1]: 
                        left += 1
                else:
                    right -= 1
                    while right < left and numbers[right] == numbers[right-1]: 
                        right -= 1
        return results
posted @ 2018-10-15 16:59  narjaja  阅读(118)  评论(0编辑  收藏  举报