题目
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
*注意:答案中不可以包含重复的三元组。
示例
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
解法
使用排序加双指针的方法
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n=len(nums)
if not nums or n<3: #判断特殊条件
return []
ans=[]
nums.sort() #排序
for i in range(n):
if nums[i]>0: #如果最小的数都大于零,则推出循环
return ans
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:
ans.append([nums[i],nums[L],nums[R]])
while(L<R and nums[R-1]==nums[R]): #排除重复解
R-=1
while(L<R and nums[L+1]==nums[L]): #排除重复解
L+=1
L+=1
R-=1
elif nums[i]+nums[L]+nums[R]>0: #大于零则右指针左移
R-=1
elif nums[i]+nums[L]+nums[R]<0: #小于零则左指针右移
L+=1
return ans