描述
给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。
在三元组(a, b, c),要求a <= b <= c。
结果不能包含重复的三元组。
您在真实的面试中是否遇到过这个题?
是
样例
如S = {-1 0 1 2 -1 -4}, 你需要返回的三元组集合的是:
(-1, 0, 1)
(-1, -1, 2)
我只能说这一题很有意思,这一题是上一题的升级版,具体可见:https://blog.csdn.net/wenqiwenqi123/article/details/80791277
那么这一题怎么做呢?就是先排序,使得a<=b<=c。因为a+b+c=0也就是说b+c=-a,所以需要遍历一遍数组去找所有的a值,这样跟上一题就一样了,target=-a而已。但是因为我们使得a<=b<=c,那么我们在遍历整个数组的时候,只需要去a的右边找b和c的值。
需要特别注意的是,为了使得在取数字的时候不重复,需要加几个while和if判断一下此数字是否和前一个数字相同:
class Solution:
"""
@param numbers: Give an array numbers of n integer
@return: Find all unique triplets in the array which gives the sum of zero.
"""
def threeSum(self, numbers):
# write your code here
def twoSum(nums, target):
# write your code here
nums = sorted(nums)
start, end = 0, len(nums) - 1
tworesult=[]
while (start < end):
# 防止数字重复选取
while(start<end and start!=0 and nums[start]==nums[start-1]):
start+=1
while(start<end and end!=len(nums)-1 and nums[end]==nums[end+1]):
end-=1
if(start==end):break
sum = nums[start] + nums[end]
if (sum < target):
start += 1
continue
elif (sum > target):
end -= 1
continue
else:
tworesult.append([nums[start], nums[end]])
start+=1
end-=1
return tworesult
numbers=sorted(numbers)
totalresult=[]
for i in range(len(numbers)):
# 防止数字重复选取
if(i!=0 and numbers[i]==numbers[i-1]):
continue
if(i+1<len(numbers)):
result=twoSum(numbers[i+1:],-numbers[i])
for j in range(len(result)):
if(numbers[i]+result[j][0]+result[j][1]==0):
totalresult.append([numbers[i]]+result[j])
continue
return totalresult
s = Solution()
print(s.threeSum([1,0,-1,-1,-1,-1,0,1,1,1]))
# [-2,-3,5,-1,-4,5,-11,7,1,2,3,4,-7,-1,-2,-3,-4,-5]