给定一个包含n个整数的数组nums,判断nums中是否存在三个元素a,b,c,使得a+b+c=0?请找出所有的三元组。
答案不包含重复的三元组。
python:
class Solution:
def threeSum(self, nums):
if len(nums)<3:return []
res=[]
n=len(nums)
nums.sort()
for i in range(n):
if nums[i]>0:
return res
if (i>0 and nums[i]==nums[i-1]):
continue
val=nums[i]
left=i+1
right=n-1
while left<right:
if nums[left]+nums[right]+val==0:
res.append([i,left,right])
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 nums[left]+nums[right]+val>0:
right-=1
#while left<right and nums[right]==nums[right-1]:
#right-=1
else:
left+=1
#while left<right and nums[left]==nums[left+1]:
#left+=1
return res
# x=Solution()
# a=[-1, 0, 1, 2, -1, -4]
#a=[-4,-2,1,-5,-4,-4,4,-2,0,4,0,-2,3,1,-5,0]
# print(x.threeSum(a))
注意:在第二个例子中,当求和大于0时,不能因为前后相等就继续推进,因为可能两个相同的数的和与当前值加起来为0
1、如果给定target,求最接近的三个数之和呢?
python:
class Solution:
def threeSumClosed(self,nums,target):
n=len(nums)
if n<3:return None
res=float('inf')
nums.sort()
for i in range(n):
if (i>0 and nums[i]==nums[i-1]):
continue
left=i+1
right=n-1
while left <right:
cur=nums[i]+nums[left]+nums[right]
if cur==target:
return target
if abs(cur-target)<abs(res-target):
res=cur
if cur<target:
left+=1
else:right-=1
return res
# x=Solution()
# nums = [-1,2,1,-4]
# target = 1
# print(x.threeSumClosed(nums,target))