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] ]
I still remember the first I saw this problem, I immediately solve it by using two SUM. But now, this method doesn't work anymore, the test case has already changed.
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
left=0
res=[]
while left<len(nums)-2:
target=0-nums[left]
dic={}
new=nums[left+1:]
for i,item in enumerate(new):
if target-item not in dic:
dic[item]=i
else:
tmp=sorted([nums[left],target-item,new[i]])
if tmp not in res:
res=res+[tmp]
left+=1
return res
The second solution, also need to sort the nums, then use two pointers to solve the problem.
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res=[]
nums.sort()
for index in range(len(nums)-2):
if index>0 and nums[index]==nums[index-1]:
continue
left=index+1
right=len(nums)-1
while left<right:
tmp=[nums[index],nums[left],nums[right]]
s=sum(tmp)
if s==0:
res.append(tmp)
while left < right and nums[left] == nums[left + 1]:
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
left+=1
right-=1
elif s>0:
right-=1
elif s<0:
left+=1
return res