Python编程题43--三数之和

2022-01-15  本文已影响0人  wintests

题目

给定一个包含 n 个整数的列表 nums,请判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。

注意:答案中不可以包含重复的三元组。

例如:

给定一个列表:[-1, 0, 1, 2, -1, -4]
返回结果:[(-1, -1, 2), (-1, 0, 1)]

给定一个列表:[1, 2, 4]
返回结果:[]

给定一个列表:[-1, 0, 1, 2, -1, -4, 0, 2, 0, 4, -4, -2, -1, 2]
返回结果:[(-4, 0, 4), (-4, 2, 2), (-2, 0, 2), (-1, -1, 2), (-1, 0, 1), (0, 0, 0)]

实现思路1

代码实现1

def threeSum(nums):
    res = []
    nums.sort()  # 排序
    for i in range(len(nums)):
        if nums[i] > 0:  # 排序后,如果第一个数 a 大于 0 ,那么必然不存在符合条件的三元组
            break
        if i > 0 and nums[i] == nums[i - 1]:  # 第一个数 a 去重
            continue
        tmp_set = set()
        for j in range(i + 1, len(nums)):
            # 从 j > i + 2 考虑,是因为允许有2种特殊情况: (1) a = b = c = 0; (2) a为负数,b = c 且 a + b + c = 0
            if j > i + 2 and nums[j] == nums[j - 1] and nums[j] == nums[j - 2]:  # 第二个数 b 去重
                continue
            a, b, c = nums[i], nums[j], 0 - nums[i] - nums[j]
            if c in tmp_set:
                res.append((a, b, c))
                tmp_set.remove(c)  # 第三个数 c 去重
            else:
                tmp_set.add(nums[j])
    return res

实现思路2

代码实现2

def threeSum(nums):
    res = []
    nums.sort()  # 排序
    for i in range(len(nums)):
        if nums[i] > 0:  # 排序后,如果第一个数 a 大于 0 ,那么必然不存在符合条件的三元组
            break
        if i > 0 and nums[i] == nums[i - 1]:  # 第一个数 a 去重
            continue
        left, right = i + 1, len(nums) - 1
        while left < right:
            a, b, c = nums[i], nums[left], nums[right]
            if a + b + c < 0:  # nums是排好序的,此时小于0,那么需要让 b 增加,left向右移动
                left += 1
            elif a + b + c > 0:  # nums是排好序的,此时大于0,那么需要让 c 减小,right向左移动
                right -= 1
            else:
                res.append((a, b, c))
                # a 在外层循环固定保持不变,所以找到一组符合条件的 b 和 c 后,left、right都需要移动
                left += 1  # left向右移动
                right -= 1  # right向左移动
                while left < right and nums[left - 1] == nums[left]:  # 第二个数 b 去重
                    left += 1
                while left < right and nums[right] == nums[right + 1]:  # 第三个数 c 去重
                    right -= 1
    return res

更多Python编程题,等你来挑战:Python编程题汇总(持续更新中……)

上一篇 下一篇

猜你喜欢

热点阅读