Given an array S of n integers, are there elements a, b, c in S such
that a + b + c = 0? Find all unique triplets in the array which gives
the sum of zero.Note:
•Elements in a triplet (a,b,c) must be in non-descending order. (ie, a
≤ b ≤ c) •The solution set must not contain duplicate triplets.For example, given array S = {-1 0 1 2 -1 -4},
A solution set is: (-1, 0, 1) (-1, -1, 2)
**给定一个数组,以列表形式输出数组中和为0的三个数。
注意:1,这三个数不能是递减的
2,最终的列表内不能有重复三个元素**
python代码如下:
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
ans=[]
for l in range(0,len(nums)-2):
i=l+1
r=len(nums)-1
while i<r and i>l:
sum=nums[l]+nums[r]+nums[i]
if sum==0:
a=[nums[l],nums[i],nums[r]]
ans.append(a)
i+=1
elif sum>0:
r-=1
else:
i+=1
ans = set(map(tuple, ans))
return list(ans)