双指针——三数之和,这种题目就是比较恶心,处理的异常情况比较多

57. 三数之和

中文
English

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

样例

例1:

输入:[2,7,11,15]
输出:[]

例2:

输入:[-1,0,1,2,-1,-4]
输出:[[-1, 0, 1],[-1, -1, 2]]

注意事项

在三元组(a, b, c),要求a <= b <= c。

结果不能包含重复的三元组。

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
        numbers.sort()

        def find_target(nums, k, target):
            l, r = k, len(nums) - 1
            ans = []
            while l < r:
                if (r + 1 < len(nums) and nums[r] == nums[r + 1]) or 
                        (nums[l] + nums[r] > target):
                    r -= 1
                elif (l - 1 >= k and nums[l] == nums[l - 1]) or 
                        (nums[l] + nums[r] < target):
                    l += 1
                elif nums[l] + nums[r] == target:
                    ans.append([-target, nums[l], nums[r]])
                    r -= 1
                    l += 1
            return ans

        ans = []
        for i, a in enumerate(numbers):
            if a <= 0:
                if (i > 0 and numbers[i - 1] == a):
                    continue
                ans.extend(find_target(numbers, i + 1, -a))

        return ans
原文地址:https://www.cnblogs.com/bonelee/p/14265072.html