题目简介:
解题思路:
a+b+c=0,无非有一下几种情况:
1⃣️a,b,c三个数字有两个是相同的,相同的数字在数组中出现的次数必须大于1;
2⃣️a为负数,b为正数数,c小于a或者c大于b;
3⃣️c=0.(除此之外,之所以不考虑:负数<c<正数是因为恰恰这么做可以去除“重复的三元组”,比如[-3,-2,5],[-2,-3,5])
代码:
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
dict = {}
pos=[]
neg=[]
for ele in nums:
if ele not in dict:
dict[ele] = 0
dict[ele] += 1
if 0 in dict and dict[0] > 2:
result = [[0,0,0]]
else:
result = []
for ele in dict:
if ele>0:
pos.append(ele)
elif ele<0:
neg.append(ele)
for p in pos:
for n in neg:
target = -(p + n)
if target in dict:
#两个相同的整数或者负数
if target in [p,n] and dict[target]>1:
result.append([p,n,target])
elif target < n or target > p or target == 0:
result.append([n, target, p])
return result