classSolution:defthreeSum(self, nums: List[int])-> List[List[int]]:
nums.sort()
res =[]
i =0for i inrange(len(nums)):if i ==0or nums[i]>nums[i-1]:
l = i+1
r =len(nums)-1while l < r:
s = nums[i]+ nums[l]+nums[r]#找到了,加进去if s ==0:
res.append([nums[i],nums[l],nums[r]])
l +=1
r -=1#去除重复元素while l < r and nums[l]== nums[l-1]:
l +=1while r > l and nums[r]== nums[r+1]:
r -=1#大的数要变小一点右指针减一elif s>0:
r -=1else:
l +=1return res
2.利用字典记录元素数量
classSolution:defthreeSum(self, nums: List[int])-> List[List[int]]:
dic={}for ele in nums:if ele notin dic:
dic[ele]=0
dic[ele]+=1if0in dic and dic[0]>2:
rst =[[0,0,0]]else:
rst =[]
pos =[p for p in dic if p >0]
neg =[n for n in dic if n <0]for p in pos:for n in neg:
inverse =-(p + n)if inverse in dic:if inverse == p and dic[p]>1:
rst.append([n, p, p])elif inverse == n and dic[n]>1:
rst.append([n, n, p])#约定这个数的大小,防止重复elif inverse < n or inverse > p or inverse ==0:
rst.append([n, inverse, p])return rst