class Solution(object):
def threeSum(self, nums):
# 1.当nums的长度小于3的时候,直接返回[]
if len(nums) < 3:
return []
# 2.将nums分成三组:zeros,positives,negatives(零,正数,负数)
zeros, positives, negatives = 0, {}, {}
# 3.统计nums中每个数字出现的次数
for num in nums:
if num == 0:
zeros += 1
elif num > 0:
positives.setdefault(num, 0)
positives[num] += 1
else:
negatives.setdefault(num, 0)
negatives[num] += 1
# 4.相加为0的三元组可能的组成形式:3个0,两个负数一个正数,两个正数一个负数,一正一负加一零
results = []
# 5.当0的个数多余3个时,向result中添加【0,0,0】
if zeros >= 3:
results.append([0] * 3)
# 6.当正数或者负数的个数为0时,直接返回result
if len(positives) == 0 and len(negatives) == 0:
return results
else:
# 7.遍历所有的正整数
for pi in positives:
# 8.获取pi这个正整数在nums的个数
count = positives[pi]
# 9.如果pi的个数大于2个,并且-2*pi在负数集中, 即(pi+pi-2pi=0),所以向result中添加【pi,pi,-2pi]
if count >= 2 and (-2 * pi) in negatives:
results.append([pi] * 2 + [-2 * pi])
# 10.如果-pi在负数集中,并且nums中有0,即(pi-pi+0=0),所以向result中添加【pi,-pi,0]
if -pi in negatives and zeros > 0:
results.append([pi, -pi, 0])
# 11.寻找两正一负的结果
for pj in positives:
# 12.这一步是为了防止向result中添加相同的结果,例如:[-1,-1,2]和[2,-1,-1]是算同一个三元组
if pj <= pi:
continue
if -1 * (pi + pj) in negatives:
results.append([-1 * (pi + pj), pi, pj])
# 13.这里和上面的原理是一样的
for ni in negatives:
count = negatives[ni]
if count >= 2 and (-2 * ni) in positives:
results.append([ni] * 2 + [-2 * ni])
for nj in negatives:
if nj <= ni:
continue
if -1 * (ni + nj) in positives:
results.append([-1 * (ni + nj), ni, nj])
return results
力扣:15三数之和(python)
最新推荐文章于 2023-07-18 09:43:24 发布