题目
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
dic = {}
for ele in nums:
if ele not in dic:
dic[ele] = 1
else:
dic[ele] += 1
if 0 in dic and dic[0] > 2:
res = [[0, 0, 0]]
else:
res = []
pos = [p for p in dic if p > 0]
neg = [n for n in dic if n < 0]
for p in pos:
for n in neg:
inverse = -(p + n)
if inverse in dic:
if inverse in [p,n] and dic[inverse]>1:
res.append([n, inverse, p])
if n < inverse < p:
res.append([n, inverse, p])
return res
def threeSum(self, nums: List[int]) -> List[List[int]]:
lens = len(nums)
if lens < 3:
return
lis = []
nums.sort()
for i in range(lens-2):
if i == 0 or nums[i]>nums[i-1]:
r = lens -1
l = i+1
if (nums[i] + nums[r-1] + nums[r]) < 0 or (nums[i] + nums[l+1] + nums[l]) >0:
continue
while l<r:
temp = nums[i]+nums[r]+nums[l]
if temp < 0:
l = l+1
elif temp > 0:
r = r-1
else :
# if not [nums[i],nums[l],nums[r]] in lis:
lis.append([nums[i],nums[l],nums[r]])
l = l+1
r = r-1
while l < r and nums[l] == nums[l-1]:
l += 1
while r > l and nums[r] == nums[r+1]:
r -= 1
return lis