思路:排序后遍历数组,每次遍历后在该数右边设置两个指针向中间移动,如果遍历的数大于0可以直接退出。因为返回要求不重复,在指针移动的过程中碰到和移动前相同的直接跳过
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums = sorted(nums)
print(nums)
res = []
for i in range(len(nums)):
if nums[i]>0:
break
if i >=1 and nums[i]==nums[i-1]:
continue
l = i+1
r = len(nums)-1
while l<r:
if nums[i]+nums[l]+nums[r]>0:
r-=1
elif nums[i]+nums[l]+nums[r]<0:
l+=1
else:
res.append([nums[i],nums[l],nums[r]])
l+=1
r-=1
while l<r and nums[l] == nums[l-1]:
l+=1
while l<r and nums[r] == nums[r+1]:
r-=1
return res