BM54 三数之和
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
解题思路:
排序 + 两数之和
五分钟力扣 Leetcode 第15题 三数之和 Python入门算法刷题两种解法 93% 97%简单易懂_哔哩哔哩_bilibili
Python代码:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []
for i, x in enumerate(nums):
if x > 0:
break
if i > 0 and nums[i] == nums[i - 1]:
continue
target = - x
subnums = nums[i + 1:]
occ = dict()
for j, y in enumerate(subnums):
if target - y in occ:
if not res or res[-1] != [target-y, x, y]:
res.append([target-y, x, y])
occ[y] = j
return res