本题如果直接遍历,无法满足题目不重复的要求。因此采用排序加双指针的方法。
排序的目的在于方便确定指针移动方向,若遇到前后相同的数则跳过,避免重复:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res=[]
n=len(nums)
nums.sort()
if (not nums or n<3):
return []
if nums[n-1]<0:
return []
for i in range(n):
if nums[i]>0:
return res
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):
res.append([nums[i],nums[L],nums[R]])
while (L<R and nums[L]==nums[L+1]):
L=L+1
while (L<R and nums[R]==nums[R-1]):
R=R-1
L=L+1
R=R-1
elif(nums[i]+nums[L]+nums[R]<0):
L=L+1
else:
R=R-1
return res