- class Solution:
- def threeSum(self, nums: List[int]) -> List[List[int]]:
- le=len(nums)
- nums.sort()
- b=[]
- for i in range(0,le-2):
- if i>0 and nums[i] == nums[i - 1]:
- continue
- l=i+1
- r=le-1
- while l<r:
- if -nums[l]==nums[r]+nums[i]:
- b.append([nums[l],nums[r],nums[i]])
- while l<r and nums[l]==nums[l+1] :
- l+=1
- while l<r and nums[r]==nums[r-1] :
- r-=1
- r-=1
- l+=1
- elif nums[l]+nums[r]+nums[i]>0:
- r-=1
- else:
- l+=1
- return b
防止重复:
- if i > 0 and nums[i] == nums[i - 1]:
- continue
- 跳过重复元素
- l=i
- 目的使三数有序,防止重复
- result.append([nums[i], nums[left], nums[right]])
# 跳过重复的 left
while left < right and nums[left] == nums[left + 1]:
left += 1
# 跳过重复的 right
while left < right and nums[right] == nums[right - 1]:
right -= 1
#继续下一个
left += 1
right -= 1
防止溢出:
- while l<r and nums[l]==nums[l+1] :√
- while nums[l]==nums[l+1] and l<r:×
- 用例:[0,0,0]