给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
首先先排序,然后,开始找第一个数,即range(le-2),当第一个数大于0,即停止,然后设定第二个数为下一个,第三个数为最大值,若和大于0,表示右值大,则r–,并且去重,若和小于等于0,则m++,且去重。
n=sorted(nums)
le=len(n)
ans=[]
for l in range(le-2):
if l and n[l]==n[l-1]:#n[l-1]已经搜索,所以去重
continue
if n[l]>0:
break
m=l+1
r=le-1
while m<r:
su=n[l]+n[m]+n[r]
if su==0:
ans.append([n[l],n[m],n[r]])
if su>0:
r-=1
while n[r]==n[r+1] and m<r:#去重
r-=1
else:
m+=1
while n[m]==n[m-1] and m<r:#去重
m+=1
return ans
1008ms,排名23%