给定一个包含 n 个整数的数组 nums
,判断 nums
中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
思路:
1. 先排序
2. 从左向右遍历每一个数字,然后在其左边部分中找到两个数字a,b使得a+b+nums[i] == 0
重要的一点: 为什么去重要写成这样?
while l<r and (nums[r] == nums[r-1]):
r=r-1
while l<r and (nums[l] == nums[l+1]):
l=l+1
当需要去重时数组中元素的情况:
.. 代表可能中间还有元素
c .. a a .. b b ,此时c + a + b = 0 这种情况a重复了两个,b重复了两个,如果不去重的话,就出现了重复解
做法应该是:
while l < r and (nums[l] == nums[l+1]) and (nums[r] == nums[r-1]):
l=l+1
r=r-1
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
if len(nums) < 3:
return []
nums=sorted(nums)
end=len(nums)
ans=list()
for i in range(end-2):
if i>0 and nums[i] == nums[i-1]: # 如果有重复元素,则只保留最前面的即可,因为最前面的求出的是最全的,不能保留后面的重复元素,否则会出现缺项,如果都不去除会出现重复。
continue
l=i+1 # nums[i] #右边第一个元素
r=end-1 # nums[i] #右边最后一个元素
while l<r: # 双指针算法
s=nums[l]+nums[r]+nums[i]
if s>0:
r=r-1
elif s<0:
l=l+1
else: # s = 0
ans.append([nums[i],nums[l],nums[r]])
while l < r and (nums[l] == nums[l+1]) and (nums[r] == nums[r-1]): # 结果去重
l=l+1
r=r-1
l=l+1
r=r-1
return ans