给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
ans = []
nums = sorted(nums)
#print(nums)
for flag in range(len(nums)-2):
"""去重:nums[flag-1]已经搜索过了,重复nums[flag]直接跳过"""
if flag > 0 and nums[flag] == nums[flag-1]:
continue
left = flag + 1
right = len(nums) - 1
while left < right:
tmp_sum = nums[flag] + nums[left] + nums[right]
#print(tmp_sum,flag,left,right)
if tmp_sum > 0:
right -= 1
while (left < right and nums[right] == nums[right+1]): # 跳过重复
right -= 1
elif tmp_sum < 0:
left +=1
while (left < right and nums[left] == nums[left-1]): # 跳过重复
left += 1
else:
ans.append([nums[flag],nums[left],nums[right]])
right -= 1
left +=1
while (left < right and nums[right] == nums[right+1]): # 跳过重复
right -= 1
while (left < right and nums[left] == nums[left-1]): # 跳过重复
left += 1
return ans