Given an array nums
of n integers, are there elements a, b, c in nums
such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
与2sum问题类似,首先将数组排序后,每次先固定一个数,剩下的就变成了2Sum问题。注意for循环里第一个if,如果nums[i]与nums[i-1]相同的话,可以直接跳过,因为在nums[i-1]已经处理过了。还有最后一个else的部分,要跳过连续重复的部分,start和end都要跳过。这样是为了确保题目要求中结果不重复,如果不这么做会超时
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums=sorted(nums)
print(nums)
ans=[]
for i in range(len(nums)-2):
if i>0 and nums[i]==nums[i-1]:
continue
tmp=nums[i]
start=i+1
end=len(nums)-1
point=0-tmp
while start<end and start<len(nums):
t=nums[start]+nums[end]
if t<point:
start+=1
elif t>point:
end=end-1
else:
ans.append([tmp,nums[start],nums[end]])
while start<end and nums[start]==nums[start+1]:
start+=1
while start<end and nums[end]==nums[end-1]:
end=end-1
start+=1
end=end-1
return ans