给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
我看到题目一开始想法非常简单,先把原先数组排序好,然后先去除数组里的重复元素,然后开始双指针运算,然后就果不其然的超时了
lass Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res =[]
i = 0
for i in range(len(nums)-1):
if nums[i]==nums[i+1]:
nums.pop(i)
i +=1
break
for i in range(len(nums)):
l = i+1
r = len(nums)-1
while l < r:
s = nums[i] + nums[l] +nums[r]
if s ==0:
res.append([nums[i],nums[l],nums[r]])
if s<0:
l +=1
if s>0:
r -=1
return res
后来就不用删除重复元素在遇见时跳过就可以了,到后来我发现只要输出的时候不出现重复数组就行那么其实只要找到确定的三组数时将他们的相同元素跳过就可以了。
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []
for i in range(len(nums)-2):
if i>0 and nums[i] == nums[i-1]: continue
start = i + 1
end = len(nums)-1
while start < end:
su = nums[i] + nums[start] + nums[end]
if su < 0:
start += 1
elif su > 0:
end -= 1
else:
res.append([nums[i], nums[start], nums[end]])
while start < end and nums[start] == nums[start+1]:
start += 1
while start < end and nums[end] == nums[end-1]:
end -= 1
start += 1
end -= 1
return res