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
探讨了在给定整数数组中寻找三个数相加等于零的所有唯一组合的方法。提供了两种解决方案:一种使用字典辅助查找,另一种采用排序与双指针技巧,避免重复解并确保结果的有效性。
1579

被折叠的 条评论
为什么被折叠?



