领扣:三个数之和

2019-12-02  本文已影响0人  领带衬有黄金

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]

代码:

def inf(nums):
    """三数之和"""
    n = len(nums)
    if not n or n < 3:
        return None
    nums.sort()  # 排序至关重要
    res = []
    for i in range(n):
        if nums[i] > 0:
            return res
        if i > 0 and nums[i] == nums[i - 1]:
            # 跳过重复元素
            continue
        L = i + 1  # 左指针
        R = n - 1  # 右指针
        while L < R:
            if nums[i] + nums[L] + nums[R] == 0:
                res.append([nums[i], nums[L], nums[R]])
                while L < R and nums[L] == nums[L + 1]:
                    L = L + 1
                while L < R and nums[R] == nums[R - 1]:
                    R = R - 1
                L = L + 1
                R = R - 1
            elif nums[i] + nums[L] + nums[R] > 0:
                R = R - 1
            else:
                L = L + 1
    return res


nums = [-1, 0, 1, 2, -1, -4]
print(inf(nums))

上一篇下一篇

猜你喜欢

热点阅读